C++ Timer

1 time_t

time_t 计时精确秒,就是相当于获取当时的时间

1
2
3
4
5
6
#include <time.h>
time_t t;
struct tm *timeinfo;
time(&t);
timeinfo = localtime(&t);
printf("%s", asctime(timeinfo));

2 clock_t

clock_t 获取的是进程调用 CPU 的时间,多核情况下不准确

1
2
3
4
5
#include <time.h>
clock_t start, finish;
start = clock();
finish = clock();
printf("main: %f ms\n", ((double)(finish - start) / 1000));

3 gettimeofday

这种方式可以精确到微秒获取程序运行耗费的时间

1
2
3
4
5
6
#include <sys/time.h>
struct timeval start, end;
gettimeofday(&start, NULL);
gettimeofday(&end1, NULL);
double timeuse = (double)(1000000 * (end1.tv_sec - start1.tv_sec) + (end1.tv_usec - start1.tv_usec)) / 1000;
printf("%f\n", timeuse); // ms

4 std::chrono

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <chrono>
struct Timer
{
std::chrono::system_clock::time_point start, end;
std::chrono::duration<float> duration;

Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
const float seconds = duration.count();
if (seconds < 1) {
std::cout << "Timer took " << seconds * 1000.0f << "ms" << std::endl;
} else if (seconds < 60) {
std::cout << "Timer took " << seconds << "s" << std::endl;
} else {
std::cout << "Timer took " << seconds / 60 << "min" << std::endl;
}
}
};

C++ Timer
https://laplac2.github.io/cpp/timer/
作者
Laplace
发布于
2022年3月19日
许可协议