正在计算线程内的时间

Calculating time within threads

本文关键字:时间 线程 计算      更新时间:2023-10-16

我的目标是通过查看线程运行所需的时间来计算线程的性能,但我遇到了一些问题:

我的代码如下:

#包括

thread() {
   struct timeval start, finish;
   gettimeofday(&start, NULL);
     -- code -- 
   gettimeofday(&start, NULL);
   double dif = ((end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)*0.000001);
   printf("%f", dif);
}

我希望我的代码以秒和毫秒的格式打印,比如:3.252或类似的格式,但我得到的是:0.1615680.161717。

有人知道如何将这种格式转换为标准的x.xxxx秒版本吗?

C++11的chrono库使这一切变得简单。有多容易?这很简单:

要求包括:

#include <chrono>

螺纹体:

std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
//--code--
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end-start;
std::cout << elapsed.count() << std::endl;

使用的库和函数链接:

chrono

high_resolution_clock

duration

作为额外的奖励,它不仅仅适用于Linux。

打印double:printf("%lf", dif);

编辑(更正):无论说明符是%f还是%lf,参数都会升级为double

此外,您使用的变量不一致。对gettimeofday的两个调用都使用start变量。end在哪里使用?