c++ - 获取 CPU 滴答和测量时间

标签 c++ time cpu clock c++-chrono

所以我想测量 C++ 中某些函数的时间,并且我尝试了很多方法。这是我的最终代码:

auto start = chrono::steady_clock::now();
clStart = clock();

for (int o=0; o<100;o++)
{
    sin(o);
   // Sleep(1);
}

auto end = chrono::steady_clock::now();
clEnd = clock();

auto difTime = end-start;
diff = chrono::duration <double,milli> (difTime).count(); //gives me 0
diffTicks = clEnd-clStart; //0 as well

当我在里面插入例如 Sleep() 函数时它工作正常但是当使用 math.h 中的 sin 时我总是得到 0 时间。这是为什么?我知道它可能已优化但 0?我想将它与其他 sin 实现进行比较,但我不确定这里有什么问题。

最佳答案

计算100罪的时间很短,应该用

auto start = chrono::steady_clock::now();
clStart = clock();

for (int o=0; o<100000;o++)
{
    sin(o);
   // Sleep(1);
}

auto end = chrono::steady_clock::now();
clEnd = clock();

auto difTime = end-start;
diff = chrono::duration <double,milli> (difTime).count();
diffTicks = clEnd-clStart;

相反。

此外,您的代码以毫秒为单位。我建议你使用 chrono::duration <double, nano> (diff).count()它使用纳秒来提高精度。


来自文档:

The only data stored in a duration is a tick count of type Rep. If Rep is floating point, then the duration can represent fractions of ticks. Period is included as part of the duration's type, and is only used when converting between different durations.

这意味着这不是您正在测量的 CPU 节拍数

关于c++ - 获取 CPU 滴答和测量时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430509/

相关文章:

c++ - QWidget 简单,只有标题和图标

html - 在时间类型的 html 5 输入元素中强制使用 24 小时符号

c++ - gettimeofday,如何翻译一个linux函数

security - 为什么 CPU 推测执行不会导致 OOB 程序崩溃?

c - 哪种方法可以更快地确定奇偶性?

c++ - CPU 时间始终为零 :(

python - Caffe 多标签矩阵输入

c++ - 'using'指令如何与模板成员函数一起工作

ruby - 无方法错误 : undefined method `zone' for Time:Class

c++ - 未能重载运算符<< (c++)