THE MOMENT, THE MEMENTO

2008年05月28日

将clock_t转化为秒值在Windows与Linux平台下的差异

标签:, , — 吴德文 @ 08:20

平时写测试程序的时候常常要计算程序执行的时间,尤其是最近练习Intel多核编程时,需要判断打开openmp参数与否的执行时间的比较。

通常代码是这样写的:

#include <time.h>
clock_t start, stop;
....
start =  clock();
do_something();
stop = clock();
printf("%f", (double)(stop-start)/1000.0) ;
.....

或者是求当前时间的秒值:
double t = (double) clock()/1000.0;

但是这样的代码在Windows平台下是正确的(当然会这样写也是因为上Intel培训课时,例程都是这么写的 ),而到了Linux平台下,这个程序就错了,会发现时间一下多了1000倍。

事实上,clock_t的值转换为秒应该是除以CLOCKS_PER_SEC这个宏,而这个宏在Windows平台下是1000,而到了Linux平台下就是1000000了。

因此程序正确的写法是:

#include <time.h>
clock_t start, stop;
....
start =  clock();
do_something();
stop = clock();
printf("%f", (double)(stop-start)/(double)CLOCKS_PER_SEC) ;
.....

这样才能保证程序在跨平台移植时的正确性。


Related:

评论暂缺 »

还没有任何评论。

这篇文章上的评论 RSS feed TrackBack URI

留下评论

You must be logged in to post a comment.

Valid XHTML 1.1 Valid CSS! Creative Commons License WordPress 所驱动