C 中经过的时间
#include <time.h>
time_t start,end;
time (&start);
//code here
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );
我的开始时间和结束时间均为 0.000。我不明白错误的根源。
另外,最好使用 time(start) 和 time(end) 或 start=clock() 和 end=clock() 来计算经过的时间。
#include <time.h>
time_t start,end;
time (&start);
//code here
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );
I'm getting 0.000 for both start and end times. I'm not understanding the source of error.
Also is it better to use time(start) and time(end) or start=clock() and end=clock() for computing the elapsed time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在大多数(几乎所有?)系统上,
time()
的粒度仅为一秒,因此无法用它来测量任何亚秒的时间长度。如果您使用的是 Unix,请尝试使用gettimeofday
代替。On most (practically all?) systems,
time()
only has a granularity of one second, so any sub-second lengths of time can't be measured with it. If you're on Unix, try usinggettimeofday
instead.如果您确实想使用
clock()
,请确保您了解它仅测量CPU 时间。此外,要转换为秒,您需要除以CLOCKS_PER_SEC
。If you do want to use
clock()
make sure you understand that it measures CPU time only. Also, to convert to seconds, you need to divide byCLOCKS_PER_SEC
.出于分析目的,简短的代码摘录通常不会花费足够长的时间来运行。一种常见的技术是重复调用很多(数百万)次,然后将得到的时间增量除以迭代计数。伪代码:
如果你想要准确性,你可以减少循环开销。例如:
Short excerpts of code typically don't take long enough to run for profiling purposes. A common technique is to repeat the call many many (millions) times and then divide the resultant time delta with the iteration count. Pseudo-code:
If you want accuracy, you can discount the loop overhead. For example:
时间
(最多)有第二个解决。如果您的代码运行时间远少于该值,则您不太可能看到差异。使用分析器(例如 *nix 上的 gprof,OS X 上的工具;对于 Windows,请参阅“使用 Eclipse 时在 Windows 上分析 C 代码”)来为代码计时。
time
has (at best) second resolution. If your code runs in much less than that, you aren't likely to see a difference.Use a profiler (such a gprof on *nix, Instruments on OS X; for Windows, see "Profiling C code on Windows when using Eclipse") to time your code.
您在测量之间使用的代码运行得太快。刚刚尝试了你的代码打印从 0 到 99,999 的数字,我得到了
The code you're using between the measurements is running too fast. Just tried your code printing numbers from 0 till 99,999 and I got
您的代码运行时间不到一秒。
Your code is taking less than a second to run.