在Windows及Linux下获取毫秒级运行时间的方法

在Windows下获取毫秒级运行时间的方法

  1. 头文件:<Windows.h>
  2. 函数原型:
    /*获取时钟频率,保存在结构LARGE_INTEGER中***/
         WINBASEAPI
         BOOL
         WINAPI
         QueryPerformanceFrequency(
         _Out_ LARGE_INTEGER * lpFrequency
         );
         /*获取从某个时间点开始的时钟周期数,保存在结构LARGE_INTEGER中**/
         WINBASEAPI
         BOOL
         WINAPI
         QueryPerformanceFrequency(
         _Out_ LARGE_INTEGER * lpFrequency
         );
  3.  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获取时钟周期数。

  4. 方法:

    1) 调用QueryPerformanceFrequency()获取时钟频率

    2) 在待测部分的首尾分别调用QueryPerformanceCounter()获取两个时间点的时钟周期数

    3) 将两个节点的时钟周期数差值除以时钟频率即可得到测试部分的运行时间

    参考代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <Windows.h>
#define SIZE 100
using 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 for
for (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;
}
View Code

在Linux下获取毫秒级运行时间的方法

  1. 头文件<sys/time.h> 
  2. 函数原型:
    int gettimeofday(struct timeval *tv, struct timezone *tz);
         struct timeval {
         time_t tv_sec; /* seconds */
         suseconds_t tv_usec; /* microseconds */
         };

    参考代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
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;
}
View Code

 参考资料:http://www.ibm.com/developerworks/cn/linux/sdk/rt/part1/index.html

转载于:https://www.cnblogs.com/chensu/p/5483594.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值