[英]c++ implementing clock to measure execution time
I have written a program in c++ and am trying to measure the time it takes to execute completely 我已经用C ++编写了一个程序,试图测量完全执行所花费的时间
int main (int argc, char**argv){
clock_t tStart = clock();
//doing my program's work here
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
My issue is that it will always print out 0.00s for the execution time. 我的问题是,它将始终在执行时间内打印出0.00s。 Could this be due to using multiple pthreads in my program (my program uses pthread_join to make sure that all threads have completed executing so I don't think this should be an issue)?
可能是由于我的程序中使用了多个pthread(我的程序使用pthread_join来确保所有线程都已完成执行,所以我认为这不应该成为问题)吗?
edit: //doing program's work =... 编辑://正在做程序的工作= ...
for(i = 0;i<4;i++){
err = pthread_create(&threads[i], NULL, print, NULL);
pthread_join(threads[i], NULL);
}
void *print(void *data){
printf("hello world");
}
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
All three of your arithmetic operands are integers, so you perform integer division and get 0
. 您的所有三个算术操作数都是整数,因此您执行整数除法并得到
0
。
Cast either the LHS or the RHS of the /
symbol to a floating-point type. 将
/
符号的LHS或RHS强制转换为浮点类型。 And run your code more times! 并多次运行您的代码! Your benchmark is useless if it measures just a single run (which is pretty evident since you got
0
, not 1
or like 300
or something). 如果仅测量一次运行,则基准测试是无用的(这很明显,因为您得到
0
,而不是1
或类似300
或类似值)。
It really depends on what is in //doing my program's work here
. 它确实取决于
//doing my program's work here
。 If it is kicking off other threads, then you will definitely need to wait or poll to get a time. 如果它正在启动其他线程,那么您肯定需要等待或轮询才能获得时间。 Show the code to get more help!
显示代码以获得更多帮助! In a similar situation I was in recently, however, it turned out that my code was actually running in less than 0.01 seconds.
但是,在最近的类似情况下,事实证明我的代码实际上在不到0.01秒的时间内运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.