Posted on 2009-01-22 16:01
Prayer 閱讀(2062)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C/C++
突然要用到C程序里調(diào)用當(dāng)前時(shí)間,來(lái)測(cè)試一段代碼的運(yùn)行時(shí)間。找了一下是否有可以調(diào)用的庫(kù)函數(shù),沒(méi)想到真的有:gettimeofday。因?yàn)檫@里的這個(gè)應(yīng)用蠻常用的,所以留個(gè)記錄在此。
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct timeval
5 {
6 long tv_sec; /* 秒數(shù) */
7 long tv_usec; /* 微秒數(shù) */
8 };
9
10 struct timezone
11 {
12 int tv_minuteswest;
13 int tv_dsttime;
14 };
15
16 int gettimeofday(struct timeval *tv,struct timezone *tz);
17
18 void function()
19 {
20 // function to run some time consuming codes
21 }
22
23 int main(int argc, char *argv[])
24 {
25 struct timeval tpstart,tpend;
26 float timespend;
27
28 gettimeofday(&tpstart,NULL);
29 function();
30 gettimeofday(&tpend,NULL);
31 timespend = tpend.tv_sec - tpstart.tv_sec;
32 printf("Time Spend: %d", timespend);
33 return EXIT_SUCCESS;
34 }