下面的一段代码产生了一个非常奇怪的输出,我不知道为什么。 它应该是我的其他测试程序非常原始的基准。无论执行cmd行参数时执行了多少次可执行文件,都会计算几次和时钟周期,然后计算mean和stddev(很好,尚未完全实现,但您明白了)。std :: for_each与函数对象
#include <algorithm>
#include <cmath>
#include <ctime>
#include <iostream>
#include <numeric>
#include <vector>
class SRS{
public:
SRS(double p1):mean(p1), srs(0.0){std::cout << this->mean << std::endl;} //DEBUG
double operator()(unsigned p1){
this->srs += std::pow(this->mean - (double)p1, 2.0);
std::cout << p1 << " " << this->srs << std::endl; //DEBUG
}
double getSrs(){
return this->srs;
}
private:
double mean;
double srs;
};
int main(int argc, char* argv[]){
unsigned nCyc;
if(argc<3){nCyc=1000;}else{nCyc=std::stoi(argv[2]);}
std::vector<clock_t> c{};
for(unsigned u = 0; u<nCyc; u+=1){
clock_t t = clock();
system(argv[1]); //this is stupid and dangerous
t = clock() - t;
c.push_back(t);
}
clock_t clkSum = std::accumulate(c.begin(), c.end(), 0);
double clkMean = (double)clkSum/(double)nCyc;
SRS srs(clkMean);
std::for_each(c.begin(), c.end(), srs);
std::cout << "The program ran for " << clkMean << " +/- " << srs.getSrs() << " clock cycles" << std::endl;
return 0;
}
令我百思不解的是,srs.getSrs()总是返回任何值分配给SRS ::由c'tor SRS(这是0.0这里)。 std :: for_each是在创建流的输出后计算的,或者是std :: for_each在执行后将函数对象恢复为原来的状态?
'的std :: for_each',就像在标准库中最(所有?)算法,接受函数对象*通过值*。 –
仅供参考,您的'operator()'被定义为返回一个'double',但您不返回任何东西。 'for_each'不应该使用它,但它仍然是UB。 – Kevin