计算一个巨大的 c++ 的运行时间程序
建议的估计时间的方法是使用clock()函数,然后将CPU周期数除以周期/秒。
我的问题是我尝试运行的程序需要很多时间(以小时为单位)。这意味着clock()函数(返回一个long int)返回一个垃圾值(因为max long int对于这个来说不够大)
有什么建议(除了估计内部循环的时间并将它们相加或其他什么)?
long t1 = clock();
function();
long t2=clock();
time = ((double)t2 - t1) / CLOCKS_PER_SEC
the suggested method of estimating the time is using the clock() function and then dividing the count of cpu cycles by cycles/second.
My problem is that the program i am trying to run takes a lot of time (in hours). This means the clock() function (that returns a long int) returns a garbage value (because max long int is not big enough for this)
Any suggestions (apart from estimating time for internal loops and adding them up or something) ?
long t1 = clock();
function();
long t2=clock();
time = ((double)t2 - t1) / CLOCKS_PER_SEC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果你在 Linux / Unix 下运行它,你可以直接说:
If you are running it under Linux / Unix you can just say:
从百分比错误的角度思考问题。
如果您的程序需要几个小时才能运行(假设 4 小时...或 14,400 秒),则 1/2% 错误为 72 秒或稍长一些不到一分钟。
换句话说,要获得精确到百分之 1/2 以内的答案,您只需将时间精确到分钟即可。假设手持秒表可以计时到一秒甚至 1/10 秒,那么您的误差将微不足道。
我的观点是,您只需使用秒计时器或手持秒表就可以准确测量您的程序。
Think of the problem in terms of percentage error.
If your program takes hours to run, (suppose 4 hours... or 14,400 seconds), then 1/2% error is 72 seconds, or slightly more than a minute.
In other words, to get an accurate answer to within 1/2 of one percent, you only need to time to the nearest minute. Assuming a hand-held stopwatch can time to within a second, or even 1/10th of a second, your error will be insignificantly small.
My point is, you could get an accurate measure of your program just using a seconds-timer or a handheld stopwatch.
如果程序长时间运行,那么亚秒级精度可能不是特别重要。在这种情况下,为什么不直接调用 time() 呢?
If the program is long running then sub-second accuracy is probably not particularly important. In that case, why not just call
time()
?gettimeofday()
函数 gettimeofday() 和 settimeofday() 可以获取时间。 tv 参数是一个 struct timeval(如 中指定):
time_t 至少为 32 位,因此它可以存储小时。
gettimeofday()
The functions gettimeofday() and settimeofday() can get the time. The tv argument is a struct timeval (as specified in ):
time_t is at least 32 bit, so it can store hours.
如果精度(由像 queryPerformanceTimer 这样的 win 调用给出)并不重要,我会采用 getTimeofTheDay 类型的方法(由 @osgx 建议)。
I would go with the getTimeofTheDay kind of an approach (suggested by @osgx) if the precision (given by win calls like queryPerformanceTimer) is not important.
Boost 计时器效果很好。
Boost timers work well.
}
}