您的位置:首页 > 编程语言 > C语言/C++

如何测量一个程序的CPU时间/程序的运行时间

2018-03-12 22:40 477 查看

CPU时间的定义

CPU时间指标是CPU上花费的时间,不包括等待I/O或运行其他程序的时间。CPU时间进一步划分为用于用户程序的时间和操作系统为用户服务花去的CPU时间。(《计算机组成与设计》第五版)

为了不误导大家

对于一个程序来说,一个程序的CPU时间是指这个程序占用CPU的时间。但往往在一个程序运行过程中,CPU可能也会被其他程序占用,所以以下的测量方法,其实是一种近似测量CPU时间的方法,实际上测量的是程序的运行时间。

介绍几种测量程序运行时间的方法(C++)

1)clock()函数

头文件 ctime

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock);若挂钟时间不可取,则返回-1。其中clock_t是用来保存时间的数据类型。(百度百科)

单位为s,精度较低

#include<iostream>
#include<ctime>
using namespace std;
int main(){
clock_t begin,end;
begin = clock();
int a=1;
for(int i=0;i<100000;i++){
for(int j=0;j<1000;j++)
a+=2;
}
end = clock();
float time = float(end-begin)/float( CLOCKS_PER_SEC);
cout<<time<<"s"<<endl;
return 0;
}


2)GetTickCount()函数

头文件 windows.h (非windows 系统需要加WinBase.h)

GetTickCount返回(retrieve)从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。(百度百科)

其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行(百度百科)

#include <iostream>
#include <windows.h>
//#include <WinBase.h>
//#include <ctime>
using namespace std;
int main(){
double begin,end;
begin = GetTickCount();

int a=1;
for(int i=0;i<100000;i++){
for(int j=0;j<1000;j++)
a+=2;
}
end = GetTickCount();
cout<<end - begin<<endl;

return 0;
}


3)gettimeofday()函数

头文件sys/time.h

int gettimeofday(struct timeval*tv, struct timezone *tz)

timeval是从1970年1月1日到现在的时间。sec是秒数,usec是微秒数,精度高达微秒。

#include<iostream>
#include <sys/time.h>
using namespace std;
int main(){
timeval begin,end;
gettimeofday(&begin,NULL);

int a=1;
for(int i=0;i<100000;i++){
for(int j=0;j<1000;j++)
a+=2;
}
gettimeofday(&end,NULL);
int usec = end.tv_usec-begin.tv_usec;
if(usec<0) {
usec+=1000000;
end.tv_sec-=1;
}
cout<<end.tv_sec-begin.tv_sec<<"."<<usec<<"ms"<<endl;
cout<<end.tv_sec<<"."<<end.tv_usec<<" "<<begin.tv_sec<<"."<<begin.tv_usec;

return 0;
}


4)QueryPerformanceFrequency()函数和QueryPerformanceCounter()函数

QueryPerformanceCounter()记录了程序运行的滴答数,

QueryPerformanceFrequency()提供了每微秒的滴答数

数据类型是LARGE_INTEGER

#include<windows.h>
#include<iostream>
using namespace std;
int main()
{
double time=0;
double counts=0;
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);//开始计时
for(int i=0;i<99999;i++)
{
counts++;
}
QueryPerformanceCounter(&nEndTime);//停止计时
time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart;//计算程序执行时间单位为s
cout<<"程序执行时间:"<<time<<"us"<<endl;
}  //来自博客http://blog.csdn.net/u012286517/article/details/50331865
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息