最近在跑一些程序,需要計算程序運行的時間,然後搜索了一下相關的材料,發現下面的一個比較好的方法,可以實現毫秒級的計時:
#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(<ime1); //start time s
//work
time(<ime2); //end time sec
ftime(&tstruct2); //end time ms
tmp_time = (ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm);
下面的代碼是一個可以在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);
}