gpt4 book ai didi

c - 如何在 Linux 中创建高分辨率计时器来测量程序性能?

转载 作者:IT老高 更新时间:2023-10-28 12:40:10 24 4
gpt4 key购买 nike

我正在尝试比较 GPU 和 CPU 的性能。对于 NVIDIA GPU,我一直在使用 cudaEvent_t 类型来获得非常精确的计时。

对于 CPU,我一直在使用以下代码:

// Timers
clock_t start, stop;
float elapsedTime = 0;

// Capture the start time

start = clock();

// Do something here
.......

// Capture the stop time
stop = clock();
// Retrieve time elapsed in milliseconds
elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f;

显然,仅当您以秒为单位计算时,该段代码才有效。而且,有时结果很奇怪。

有人知道在 Linux 中创建高分辨率计时器的方法吗?

最佳答案

查看 clock_gettime ,这是高分辨率计时器的 POSIX 接口(interface)。

如果在阅读了手册页后,您对 CLOCK_REALTIMECLOCK_MONOTONIC 之间的区别感到疑惑,请参阅 Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

完整示例请参见以下页面:http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/

#include <iostream>
#include <time.h>
using namespace std;

timespec diff(timespec start, timespec end);

int main()
{
timespec time1, time2;
int temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
for (int i = 0; i< 242000000; i++)
temp+=temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
return 0;
}

timespec diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}

关于c - 如何在 Linux 中创建高分辨率计时器来测量程序性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com