为什么我不能查看运行时间(纳秒)

Why can I not view the run time (nanoseconds)?

本文关键字:纳秒 运行时间 不能 为什么      更新时间:2023-10-16

我试图查看我的代码的运行时是什么。这段代码是我对欧拉项目第5题的尝试。当我尝试输出运行时间时,它给出了0ns。

#define MAX_DIVISOR 20
bool isDivisible(long, int);
int main() {
auto begin = std::chrono::high_resolution_clock::now();
int d = 2;
long inc = 1;
long i = 1;
while (d < (MAX_DIVISOR + 1)) {
    if ((i % d) == 0) {
        inc = i;
        i = inc;
        d++;
    }
    else {
        i += inc;
    }
}
auto end = std::chrono::high_resolution_clock::now();
printf("Run time: %llu nsn", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count())); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;
system("pause");
return 0;

}

std::chrono::high_resolution_clock::now()的计时解析取决于系统。

你可以用这里的一小段代码找到一个数量级(edit:在这里你有一个更准确的版本):

chrono::nanoseconds mn(1000000000);  // asuming the resolution is higher
for (int i = 0; i < 5; i++) {
    using namespace std::chrono; 
    nanoseconds dt; 
    long d = 1000 * pow(10, i);
    for (long e = 0; e < 10; e++) {
        long j = d + e*pow(10, i)*100;
        cout << j << " ";
        auto begin = high_resolution_clock::now();
        while (j>0)
            k = ((j-- << 2) + 1) % (rand() + 100);
        auto end = high_resolution_clock::now();
        dt = duration_cast<nanoseconds>(end - begin);
        cout << dt.count() << "ns = " 
             << duration_cast<milliseconds>(dt).count() << " ms" << endl;
        if (dt > nanoseconds(0) && dt < mn)
            mn = dt;
    }
}
cout << "Minimum resolution observed: " << mn.count() << "nsn";

,其中k为全局volatile long k;,以避免优化器干扰过多。

在windows下,我在这里获得15ms。然后你有特定平台的选择。对于窗口,有一个高性能时钟,使您能够测量时间低于10µs的范围(见这里http://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx),但仍然不在纳秒范围内。

如果您希望对代码进行非常精确的计时,您可以在一个大循环中重新执行它,并将总时间除以迭代次数。

您要做的估计是不精确的,更好的方法是测量您程序的CPU时间消耗(因为其他进程也与您的进程并发运行,所以如果CPU密集型任务与您的进程并行运行,您试图测量的时间可能会受到很大影响)。
所以我建议如果你想评估你的代码性能,使用已经实现的分析器。

考虑到你的任务,操作系统不能提供所需的时间精度,你需要增加你试图估计的总时间,最简单的方法-运行程序n次&计算平均值,这种方法提供了这样的优势,通过平均,您可以消除由于CPU密集型任务与您的进程并发运行而产生的错误。

下面是我认为可能实现的代码片段:

#include <iostream>
using namespace std;
#define MAX_DIVISOR 20
bool isDivisible(long, int);
void doRoutine()
{
  int d = 2;
  long inc = 1;
  long i = 1;
  while (d < (MAX_DIVISOR + 1)) 
  {
        if (isDivisible(i, d)) 
        {
            inc = i;
            i = inc;
            d++;
        }
        else 
        {
            i += inc;
        }
   }
}
int main() {
auto begin = std::chrono::high_resolution_clock::now();
const int nOfTrials = 1000000;
for (int i = 0; i < nOfTrials; ++i)
    doRoutine();
auto end = std::chrono::high_resolution_clock::now();
printf("Run time: %llu nsn", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()/ nOfTrials)); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;
system("pause");
return 0;