程序耗时性能测试
# RDTSC
- 使用rdtsc指令: http://blog.chinaunix.net/uid-24774106-id-2779245.html (opens new window)
- 多核时代不宜再用 x86 的 RDTSC 指令测试指令周期和时间 https://blog.csdn.net/wh8_2011/article/details/52965538 (opens new window)
# c++ chrono三种时钟
参考: http://www.cplusplus.com/reference/chrono/ (opens new window)
steady_clock 是单调的时钟,相当于教练手中的秒表;只会增长,适合用于记录程序耗时;为了保证只会增长,开销会大一点。
system_clock 是系统的时钟;因为系统的时钟可以修改;甚至可以网络对时; 所以用系统时间计算时间差可能不准。
high_resolution_clock 是当前系统能够提供的最高精度的时钟, 是 steady_clock 或 system_clock 的 typedef 。不同的机器上实现不一样。
using high_resolution_clock = system_clock;
# steady_clock
#include <chrono>
#include <iostream>
using namespace std;
int main() {
using namespace chrono;
steady_clock::time_point t1 = steady_clock::now();
// do something
for(int i=0; i<test_size; ++i){
cout<<"*";
}
cout<<endl;
steady_clock::time_point t2 = steady_clock::now();
duration<double, micro> time_span = (duration<double, micro>)(t2 - t1);
cout<<"cost us:" << (time_span).count()/test_size <<endl;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# C语言 clock_gettime()
参考: https://blog.csdn.net/qq_33706673/article/details/79039217 (opens new window)
clock_gettime(获取指定时钟的时间值)
#include <time.h>
int clock_gettime( clockid_t clock_id, struct timespec * tp );
// 获取数据的结构体定义如下:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds 纳秒*/
};
2
3
4
5
6
7
8
9
说明:clock_id指定要获取时间的时钟,根据Posix的指定可以是以下值:
CLOCK_REALTIME 0 Systemwide realtime clock. 系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户该成其他,则对应的时间相应改变。
CLOCK_MONOTONIC 1 Represents monotonic time. Cannot be set. 从系统启动这一刻起开始计时,不受系统时间被用户改变的影响。
CLOCK_PROCESS_CPUTIME_ID 2 High resolution per-process timer. 本进程到当前代码系统CPU花费的时间
CLOCK_THREAD_CPUTIME_ID 3 Thread-specific timer. 本线程到当前代码系统CPU花费的时间
CLOCK_REALTIME_HR 4 High resolution version of CLOCK_REALTIME.
CLOCK_MONOTONIC_HR 5 High resolution version of CLOCK_MONOTONIC.
建议使用CLOCK_MONOTONIC或者CLOCK_REALTIME来测量时间。