计算程序的运行时间

来源:互联网 发布:青少年性犯罪数据 编辑:程序博客网 时间:2024/04/20 09:33
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#include <stdio.h>#include <tchar.h>#include <cstdlib>#include <iostream>#include <sys/timeb.h>#include <ctime>#include <climits>using namespace std;int _tmain(int argc, _TCHAR* argv[]){    //计时方式一    time_t start = 0,end = 0;    time(&start);    for(int i=0; i < numeric_limits<int>::max(); i++)    {        double circle = 3.1415962*i;  //浮点运算比较耗时,循环最大整数次数    }    time(&end);    cout << "采用计时方式一(精确到秒):循环语句运行了:" << (end-start) << "秒" << endl;        //计时方式二    struct timeb startTime , endTime;    ftime(&startTime);    for(int i=0; i < numeric_limits<int>::max(); i++)    {        double circle = 3.1415962*i;  //浮点运算比较耗时,循环最大整数次数    }    ftime(&endTime);    cout << "采用计时方式二(精确到毫秒):循环语句运行了:" << (endTime.time-startTime.time)*1000 + (endTime.millitm - startTime.millitm) << "毫秒" << endl;    //计时方式三    clock_t startCTime , endCTime;      startCTime = clock();   //clock函数返回CPU时钟计时单元(clock tick)数,还有一个常量表示一秒钟有多少个时钟计时单元,可以用clock()/CLOCKS_PER_SEC来求取时间    for(int i=0; i < numeric_limits<int>::max(); i++)    {        double circle = 3.1415962*i;  //浮点运算比较耗时,循环最大整数次数    }    endCTime = clock();    cout << "采用计时方式三(好像有些延迟,精确到秒):循环语句运行了:" << double((endCTime-startCTime)/CLOCKS_PER_SEC) << "秒" << endl;    cout << "综合比较上述三种种计时方式,方式二能够精确到毫秒级别,比方式一和三都较好。此外在Windows API中还有其他的计时函数,用法都大同小异,在此就不做介绍了。" << endl;        system("pause");    return 0;}

0 0
原创粉丝点击