C中计算程序运行时间差(毫秒级)
生活随笔
收集整理的這篇文章主要介紹了
C中计算程序运行时间差(毫秒级)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近在跑一些程序,需要計算程序運行的時間,然后搜索了一下相關的材料,發現下面的一個比較好的方法,可以實現毫秒級的計時:
#include <sys/timeb.h> #if defined(WIN32) # define TIMEB? _timeb #define ftime _ftime #else #define TIMEB timeb #endiftime_t ltime1, ltime2, tmp_time;struct TIMEB tstruct1, tstruct2;ftime(&tstruct1); //start time mstime(<ime1); //start time s//worktime(<ime2); //end time secftime(&tstruct2); //end time mstmp_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); }?
總結
以上是生活随笔為你收集整理的C中计算程序运行时间差(毫秒级)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: setsockopt()和getsock
- 下一篇: nginx开启core dump文件