C++时钟保持为零

toe*_*ebs 2 c++ time.h

我正在尝试获取我的程序的已用时间.其实,我想我应该使用yclock()time.h.但它在程序的所有阶段都保持为零,尽管我添加了10 ^ 5个数字(必须消耗一些CPU时间).我已经搜索过这个问题,看起来,运行Linux的人只有这个问题.我正在运行Ubuntu 12.04LTS.

我要比较AVX和SSE指令,所以使用time_t它不是一个真正的选择.任何提示?

这是代码:

 //Dimension of Arrays
unsigned int N = 100000;
//Fill two arrays with random numbers
unsigned  int a[N];
clock_t start_of_programm = clock();
for(int i=0;i<N;i++){
    a[i] = i;
}
clock_t after_init_of_a = clock();
unsigned  int b[N];
for(int i=0;i<N;i++){
    b[i] = i;
}
clock_t after_init_of_b = clock();

//Add the two arrays with Standard
unsigned int out[N];
for(int i = 0; i < N; ++i)
    out[i] = a[i] + b[i];
clock_t after_add = clock();

cout  << "start_of_programm " << start_of_programm  << endl; // prints
cout  << "after_init_of_a " << after_init_of_a  << endl; // prints
cout  << "after_init_of_b " << after_init_of_b  << endl; // prints
cout  << "after_add " << after_add  << endl; // prints
cout  << endl << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << endl;
Run Code Online (Sandbox Code Playgroud)

和控制台的输出.我也用printf()%d,有没有什么区别.

start_of_programm 0
after_init_of_a 0
after_init_of_b 0
after_add 0

CLOCKS_PER_SEC 1000000
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 5

clock确实返回使用的CPU时间,但粒度大约为10Hz.因此,如果您的代码不超过100毫秒,您将获得零.除非它显着超过100毫秒,否则您将无法获得非常准确的值,因为它的误差范围将在100毫秒左右.

因此,增加N或使用不同的方法来测量时间将是您的选择.std::chrono最有可能产生更准确的时间(但它会测量"壁挂时间",而不是CPU时间).

timespec t1, t2; 
clock_gettime(CLOCK_REALTIME, &t1); 
... do stuff ... 
clock_gettime(CLOCK_REALTIME, &t2); 
double t = timespec_diff(t2, t1);

double timespec_diff(timespec t2, timespec t1)
{
    double d1 = t1.tv_sec + t1.tv_nsec / 1000000000.0;
    double d2 = t2.tv_sec + t2.tv_nsec / 1000000000.0;

    return d2 - d1;
}
Run Code Online (Sandbox Code Playgroud)