C++ 时钟保持为零

标签 c++ time.h

我正在尝试获取程序的运行时间。实际上我认为我应该使用 time.h 中的 yclock()。但是它在程序的所有阶段都保持为零,尽管我添加了 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;

以及控制台的输出。我还使用了 printf()%d,没有区别。

start_of_programm 0
after_init_of_a 0
after_init_of_b 0
after_add 0

CLOCKS_PER_SEC 1000000

最佳答案

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;
}

关于C++ 时钟保持为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696505/

相关文章:

我可以在同一个文件中使用来自 time.h 的两个 tm 结构吗?

c - 在cygwin 1.7环境下使用GDB如何使gettimeofday函数调用失败?

c++ - For 循环打印一个额外的逗号

c++ - 计算线性系统的误差 - 提取每一列

c++ - iPhone编译移植代码问题: variable given same name as typedef'd type failing

c - 在文件中添加日期 - C

c - 这个程序中的ctime函数是如何工作的?

c++ - 在程序启动时自动执行代码而不违反 ODR

c++ - 允许用户跳过输入并直接按 Enter 键

c - 查找代码所花费的时间