在Windows下获取毫秒级运行时间的方法
- 头文件:<Windows.h>
- 函数原型:
/*获取时钟频率,保存在结构LARGE_INTEGER中***/ WINBASEAPI BOOL WINAPI QueryPerformanceFrequency( _Out_ LARGE_INTEGER * lpFrequency ); /*获取从某个时间点开始的时钟周期数,保存在结构LARGE_INTEGER中**/ WINBASEAPI BOOL WINAPI QueryPerformanceFrequency( _Out_ LARGE_INTEGER * lpFrequency );
- LARGE_INTEGER结构
typedef union _LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; } DUMMYSTRUCTNAME; struct { DWORD LowPart; LONG HighPart; } u; #endif //MIDL_PASS LONGLONG QuadPart; } LARGE_INTEGER;
LARGE_INTEGER为一个union,我们将使用成员QuadPart获取时钟周期数。
- 方法:
1) 调用QueryPerformanceFrequency()获取时钟频率
2) 在待测部分的首尾分别调用QueryPerformanceCounter()获取两个时间点的时钟周期数
3) 将两个节点的时钟周期数差值除以时钟频率即可得到测试部分的运行时间
参考代码:
#include#include #include #include #define SIZE 100using namespace std;int a[SIZE];int b[SIZE];int c[SIZE];int main(){//srand(time(0));for (int i = 0; i < SIZE; ++i){a[i] = rand();b[i] = rand();}LARGE_INTEGER begain, end, frequency;QueryPerformanceFrequency(&frequency);QueryPerformanceCounter(&begain);#pragma omp parallel forfor (int i = 0; i < SIZE; ++i){c[i] = a[i] * b[i];}QueryPerformanceCounter(&end);cout << "Cost time : " << (double)(end.QuadPart - begain.QuadPart) * 1000 / frequency.QuadPart << "ms" << endl;cout << begain.QuadPart << endl;}
在Linux下获取毫秒级运行时间的方法
- 头文件<sys/time.h>
- 函数原型:
int gettimeofday(struct timeval *tv, struct timezone *tz); struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ };
参考代码:
#include#include #include int main(){ struct timeval _tstart, _tend; double t1, t2; gettimeofday(&_tstart, NULL); // ToDo.. gettimeofday(&_tend, NULL); t1 = (double)_tstart.tv_sec * 1000 + (double)_tstart.tv_usec / 1000; t2 = (double)_tend.tv_sec * 1000 + (double)_tend.tv_usec / 1000; printf("Cost time : %fms\n", t2 - t1); return 0;}
参考资料:http://www.ibm.com/developerworks/cn/linux/sdk/rt/part1/index.html