我用 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;
}
我的问题是它总是打印出 0.00 秒的执行时间。这可能是因为在我的程序中使用了多个 pthread(我的程序使用 pthread_join 来确保所有线程都已完成执行,所以我认为这应该不是问题)?
编辑://做程序的工作=...
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);
所有三个算术操作数都是整数,因此您执行整数除法并得到 0
。
将 /
符号的 LHS 或 RHS 转换为浮点类型。并多次运行您的代码!如果您的基准测试仅测量一次运行(这很明显,因为您得到的是 0
,而不是 1
或类似 300
之类的东西,那么您的基准测试是无用的) .
关于c++实现时钟来测量执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29080731/