问题描述
在程序的顶部和结尾,我使用 clock() 来计算我的程序需要多长时间才能完成.不幸的是,它似乎只需要报告的一半时间.我用时间"命令仔细检查了这一点.
At the top and end of my program I use clock() to figure out how long my program takes to finish. Unfortunately, it appears to take half as long as it's reporting. I double checked this with the "time" command.
我的程序报告:45.86s 内完成
My program reports: Completed in 45.86s
时间命令报告:真正的 0m22.837s用户 0m45.735s系统0m0.152s
Time command reports: real 0m22.837s user 0m45.735s sys 0m0.152s
用我的手机计时,它在 23 秒内完成(又名:真实"时间).用户"时间是所有线程的总和,这很有意义,因为我使用的是 OpenMP.(你可以在这里阅读:'real'、'user' 和 'sys' 在 time(1) 的输出中是什么意思?)
Using my cellphone to time it, it completed in 23s (aka: the "real" time). "User" time is the sum of all threads, which would make sense since I'm using OpenMP. (You can read about it here: What do 'real', 'user' and 'sys' mean in the output of time(1)?)
那么,为什么 clock() 在用户"时间而不是实时"时间报告?是否应该使用不同的函数来计算我的程序运行了多长时间?
So, why is clock() reporting in "user" time rather than "real" time? Is there a different function I should be using to calculate how long my program has been running?
作为旁注,Windows 的时钟()按预期工作并实时"报告.
As a side note, Windows' clock() works as expected and reports in "real" time.
推荐答案
用户 0m45.735s
user 0m45.735s
clock()
根据 7.27.2.1 测量进程使用的 CPU 时间(尽其所能)
clock()
measures CPU time the process used (as good as it can) per 7.27.2.1
clock 函数返回实现对程序使用的处理器时间的最佳近似值,自一个实现定义的时代开始,仅与程序调用相关.
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.
而不是挂钟时间.因此 clock()
报告的时间接近 time
报告的 user
时间是正常且符合标准的.
and not wall clock time. Thus clock()
reporting a time close to the user
time that time
reports is normal and standard-conforming.
为了测量经过的时间,如果你可以假设 POSIX,使用 clock_gettime
可能是最好的选择,标准函数 time()
也可以用于那个,但是不是很细粒度.
To measure elapsed time, if you can assume POSIX, using clock_gettime
is probably the best option, the standard function time()
can also be used for that, but is not very fine-grained.
这篇关于C++:Linux 中的时序(使用 clock())不同步(由于 OpenMP?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!