您好,欢迎来到易妖游戏网。
搜索
您的当前位置:首页如何测量一个程序的CPU时间/程序的运行时间

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

来源:易妖游戏网

CPU时间的定义

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

为了不误导大家

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

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

1)clock()函数

#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()函数

  1. 头文件 windows.h (非windows 系统需要加WinBase.h)
  2. GetTickCount返回(retrieve)从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。(百度百科)
  3. 其最小精度为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()函数

  1. 头文件sys/time.h
  2. int gettimeofday(struct timeval*tv, struct timezone *tz)
  3. 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()函数

  1. QueryPerformanceCounter()记录了程序运行的滴答数,
  2. QueryPerformanceFrequency()提供了每微秒的滴答数
  3. 数据类型是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:///u012286517/article/details/50331865

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- vipyiyao.com 版权所有 湘ICP备2023022495号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务