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

编程入门 行业动态 更新时间:2024-10-26 08:26:14
本文介绍了为什么我看不到运行时间(纳秒)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试查看我的代码的运行时是什么.该代码是我在 Project Euler 问题 5 中的尝试.当我尝试输出运行时间时,它给出了 0ns.

I am trying to view what the run-time on my code is. The code is my attempt at Project Euler Problem 5. When I try to output the run time it gives 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 密集型任务与您的进程并行运行,则您尝试测量的时间可能会受到很大影响).因此,如果您想估计代码性能,我的建议是使用已经实现的分析器.

Estimation you are going to do is not precise, better approach is to measure CPU time consumption of you program (because other processes are also running concurrently with you process, so time that you are trying to measure can be greatly affected if CPU intensitive tasks are running in parallel with you process). So my advise use already implemented profilers if you want to estimate your code performance.

考虑到您的任务,操作系统如果没有提供所需的时间精度,您需要增加您尝试估计的总时间,最简单的方法 - 运行程序 n 次 &计算平均值,此方法提供了这样的优势,即通过平均值 - 您可以消除因与您的进程同时运行的 CPU 密集型任务而产生的错误.

Considering your task, OS if doesn`t provide needed precision for time, you need to increase total time your are trying to estimate, the esiest way - run program n times & calculate the avarage, this method provides such advantage that by avareging - you can eleminate errors that arose from CPU intensitive tasks running concurrently with you process.

这是我如何看待可能实现的代码片段:

Here is code snippet of how I see the possible implementation:

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

更多推荐

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

本文发布于:2023-11-27 20:35:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639507.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我看   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!