C中计算程序运行时间差(毫秒级)

最近在跑一些程序,需要计算程序运行的时间,然后搜索了一下相关的材料,发现下面的一个比较好的方法,可以实现毫秒级的计时:

#include <sys/timeb.h>
#if defined(WIN32)
# define  TIMEB    _timeb
# define  ftime    _ftime
#else
#define TIMEB timeb
#endif

time_t ltime1, ltime2, tmp_time;
  struct TIMEB tstruct1, tstruct2;
  
  ftime (&tstruct1);            // start time ms
  time (&ltime1);               // start time s
  
//work
  time (&ltime2);               // end time sec
  ftime (&tstruct2);            // end time ms

  tmp_time = (ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm);

 更新:2012年2月25日 12时34分28秒

下面的代码是一个可以在windows和linux平台下进行毫秒级计时的程序。

程序中是进行上万次的内存分配来耗时,演示计时的方法的。

毫秒级的计时的主要使用的函数ftime,使用ftime可以得到当前时间的毫秒和秒,从而我们可以得到毫秒级的计时。

但是如果要以毫秒为单位输出时间的话,必须使用64位的数据类型来表示。在linux上是long long,而windows下是使用__int64.并且如果使用printf的话,需要使用64位情况下对应的输出方式。不然会输出负数,这时就是溢出了。

linux下是:printf("%lld",n)

windows下是:printf(“%I64d",n)

#include <stdio.h>
#include <sys/timeb.h>
#include <stdlib.h>
#if defined(WIN32)
# define  TIMEB    _timeb
# define  ftime    _ftime
typedef __int64 TIME_T;
#else
#define TIMEB timeb
typedef long long TIME_T;
#endif
int time_interval()
{
    struct TIMEB ts1,ts2;
    TIME_T t1,t2;
    int ti;
    ftime(&ts1);//开始计时
    
//do some work
    {
        int i;
        for(i=0;i<100000;i++)
        {
            int *p=malloc(10000);
            int *q=malloc(10000);
            int *s=malloc(10000);
            int *t=malloc(10000);
            free(p);
            free(q);
            free(s);
            free(t);
        }
    }
    ftime(&ts2);//停止计时
    t1=(TIME_T)ts1.time*1000+ts1.millitm;
    printf("t1=%lld\n",t1);
    t2=(TIME_T)ts2.time*1000+ts2.millitm;
    printf("t2=%lld\n",t2);
    ti=t2-t1;//获取时间间隔,ms为单位的

    return ti;
}
int main()
{
    int ti=time_interval();
    printf("time interval=%d\n",ti);
}

 

不过其实如果只是单纯的获得时间的间隔的话,也不用考虑64位的问题,因为将两个时间的秒一级的耗时相减的话结果就比较小了,代码如下:

#include <stdio.h>
#include <sys/timeb.h>
#include <stdlib.h>
#if defined(WIN32)
# define  TIMEB    _timeb
# define  ftime    _ftime
#else
#define TIMEB timeb
#endif
int time_interval()
{
    struct TIMEB ts1,ts2;
    time_t t_sec,ti;
    ftime(&ts1);//开始计时
    
//do some work
    {
        int i;
        for(i=0;i<100000;i++)
        {
            int *p=malloc(10000);
            int *q=malloc(10000);
            int *s=malloc(10000);
            int *t=malloc(10000);
            free(p);
            free(q);
            free(s);
            free(t);
        }
    }

    ftime(&ts2);//停止计时
    t_sec=ts2.time-ts1.time;//计算秒间隔
    t_ms=ts2.millitm-ts1.millitm;//计算毫秒间隔
    ti=t_sec*1000+t_ms;

    return ti;
}
int main()
{
    int ti=time_interval();
    printf("time interval=%d\n",ti);
}


posted @ 2011-11-14 14:47  Mr.Rico  阅读(22022)  评论(0编辑  收藏  举报