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

我正在试图查看我的代码上的运行时间是什么。 代码是我在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; 

}

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

考虑到你的任务,操作系统如果不提供所需的时间精度,你需要增加你正在估计的总时间,最恶劣的方式 – 运行程序n次和计算平均值,这种方法提供了这样的优势,通过avareging – 你可以清除CPU进程中并发执行的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; 

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&#x3002; aspx ),但仍不在纳秒范围内。

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