正在计算线程内的时间
Calculating time within threads
我的目标是通过查看线程运行所需的时间来计算线程的性能,但我遇到了一些问题:
我的代码如下:
#包括
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
在哪里使用?
相关文章:
- 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?
- 在C++中使用线程查找友好号码比单个线程花费更多时间
- 分别测量每个线程上花费的 CPU 时间(C++)
- 如何在c++多线程中匹配处理时间和接收时间
- 给定使用 C++ 或 C,我如何测量在 linux 下进行线程切换需要多长时间?可能吗?
- 将线程锁定很长时间
- ::grpc::ServerReaderWriter 对象在另一个线程中一段时间后无法调用
- 即使长时间等待,C++线程也不会加入
- 锁通过线程保留的时间太长
- 查询时间/周期是针对所有内核/线程的序列化请求还是并行请求?
- 对于同一任务,线程的等待时间在 0 到 30000 微秒之间系统地切换
- 如何测量一组特定线程的 CPU 时间?
- 不完整的多线程光线追踪器花费的时间是预期的两倍
- 如何在多线程应用程序中获得花费的时间
- 在关闭应用程序期间正确关闭线程,该线程可能会运行很长时间的循环
- 使用 4 个和 8 个线程运行时执行的时间相等
- OpenMP 并行编程基于线程数与执行时间的关系
- 为什么我的多线程示例需要与任何一个相同的时间
- 在 C++20 中获取当前日期/时间是否线程安全?
- 如何找到C/C 线程使用的总时间