计算时间间隔

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值