Qt测算程序运行时间

【问题描述】程序运行时间是编程的一项重要指标,在QT中如何测算程序的运行时间呢?

测试函数:

#include <math.h>  
  
void function()  
{  
    unsigned int i,j;  
    double y;  
  
    for(i=0;i<1000;i++)  
        for(j=0;j<1000;j++)  
            y=sin((double)i);  
}  

方法1 利用QTime,其精度为ms级

#include <QDebug>  
#include <QTime>  
  
QTime time;  
  
time.start();  
function();  
  
qDebug()<<time.elapsed()/1000.0<<"s";  

运行结果:0.109 s

方法2 利用gettimeofday(),其精度为us级

#include <QDebug>  
#include <sys/time.h>  
  
struct timeval tpstart,tpend;  
float timeuse;  
  
gettimeofday(&tpstart,NULL);  
function();  
gettimeofday(&tpend,NULL);  
timeuse=(1000000*(tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec-tpstart.tv_usec)/1000000.0;  
  
qDebug()<<timeuse<<"s";  

运行结果:0.109375 s

方法3 利用clock(),其精度为ms级

#include <QDebug>  
#include <sys/time.h>  
  
double time_Start = (double)clock();  
function();  
double time_End = (double)clock();  
      
qDebug()<<(time_End - time_Start)/1000.0<<"s";  

运行结果:0.11 s

方法4 利用windows.h(VC)函数,提精度为us级

#include <QDebug>  
#include <windows.h>  
  
LARGE_INTEGER litmp;  
LONGLONG Qpart1,Qpart2,Useingtime;  
double dfMinus,dfFreq,dfTime;  
  
//获得CPU计时器的时钟频率  
QueryPerformanceFrequency(&litmp);//取得高精度运行计数器的频率f,单位是每秒多少次(n/s),  
dfFreq = (double)litmp.QuadPart;  
  
QueryPerformanceCounter(&litmp);//取得高精度运行计数器的数值  
Qpart1 = litmp.QuadPart; //开始计时  
  
function(); //待测试的计算函数等  
  
QueryPerformanceCounter(&litmp);//取得高精度运行计数器的数值  
Qpart2 = litmp.QuadPart; //终止计时  
  
dfMinus = (double)(Qpart2 - Qpart1);//计算计数器值  
dfTime = dfMinus / dfFreq;//获得对应时间,单位为秒,可以乘1000000精确到微秒级(us)  
Useingtime = dfTime*1000000;  
  
qDebug()<<dfTime<<"s";  

运行结果:0.107415 s

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值