首页 > 其他 > 详细

计算时间间隔

时间:2015-05-17 23:37:21      阅读:212      评论:0      收藏:0      [点我收藏+]

time_t 获得时间只能精确到,clock_t 获得时间能够精确到毫秒

#include <time.h>

 

clock_t start,ends;
 start=clock();

system("pause");

 ends=clock();
 cout<<ends-start<<endl;


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;

}

计算时间间隔

原文:http://blog.csdn.net/greenapple_shan/article/details/45798949

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!