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

时间:2014-07-06 10:26:47

标签: c++ windows runtime

我正在尝试查看代码的运行时间。代码是我Project Euler Problem 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 ns\n", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count())); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;

system("pause");
return 0;

}

2 个答案:

答案 0 :(得分:2)

std :: chrono :: high_resolution_clock :: now()的计时重新排序与系统有关。

您可以在这里找到一小部分代码(编辑,这里有更准确的版本):

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() << "ns\n";

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

在Windows下,我在这里获得了15ms。然后你有平台特定的替代品。对于Windows,有一个高性能的cloeck,使您能够测量10μs范围内的时间(请参阅此处http://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx),但仍然不在纳秒范围内。

如果你想非常准确地计算你的代码,你可以重新执行它一个大循环,并根据迭代次数计算总时间。

答案 1 :(得分:1)

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

考虑到你的任务,操作系统如果没有提供所需的精确时间,你需要增加你试图估计的总时间,最重要的方式 - 运行程序n次&amp;计算avarage,这种方法提供了这样的优势:通过avareging - 你可以消除因与你的进程同时运行的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 ns\n", (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()/ nOfTrials)); // Gives 0 here.
std::cout << "ANS: " << i << std::endl;

system("pause");
return 0;