一般C語言的標準函式庫只能提供毫秒等級(mini-sec, 10-3)的時間存取函式,所以我們轉而向作業系統的系統函式庫來尋求支援。在POSIX 1003.1b Real Time[6]標準中已經訂定出奈秒(nano-sec, 10-9)等級的時間存取函式,而現今的UNIX作業系統,如Solaris、Linux、FreeBSD也都已實作出符合POSIX 標準的系統函式庫。在這一系列的高精確度時間函式中,我們選擇使用clock_gettime函式來產生時間戳記,其函式的原型及參數的資料型別如下:

int clock_gettime ( clockid_t clock_id, timespec *tv )

其中第一個參數clock_id分別可以設定clockid_t型態中的三種計時器:CLOCK_REALTIME、CLOCK_virtual、CLOCK_PROF,CLOCK_REALTIME代表這個計時器是從電腦系統開始運作就開始計數,直到電腦系統電源關閉為止;而CLOCK_virtual的計時器則是在處理器執行的程序(process)是屬於使用者模式(user mode)時才會計數,其他狀況則停止計數;CLOCK_PROF計時器則是在處理器執行的程序是屬於使用者模式或系統核心模式(kernel mode)的程式才會計數。


這個函式會將計時器的值儲存成timespec的型態,整個資料結構會將時間值分為秒及奈秒兩部分,結構定義如下:

struct timespec
{
time_t tv_sec;
long int tv_nsec; /* tv_nsec is nano second */
};

請問一下我在Linux底下執行這函式時

* execute the program specified as its first argument.
* The time is printed in seconds, on standard out.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>


#define BILLION 1000000000L;


int main( int argc, char** argv )
{
struct timespec start, stop;
double accum;

if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
return EXIT_FAILURE;
}
system( argv[1] );
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
return EXIT_FAILURE;
}
accum = ( stop.tv_sec - start.tv_sec )
+ (double)( stop.tv_nsec - start.tv_nsec )
/ (double)BILLION;
printf( "%lf\n", accum );
return EXIT_SUCCESS;
}

結果出現:
[root@cluster6 mysql_c]# gcc -o main main.c
/tmp/cciqEwbR.o: In function `main':main.c:(.text+0x23): undefined reference to `clock_gettime'
:main.c:(.text+0x66): undefined reference to `clock_gettime'
collect2: ld returned 1 exit status

有#include <time.h>還是找不到clock_gettime,應該是沒有link lib,在compiler option 加上lrt或許就會通過,下次自己要用的時候再試。

 


arrow
arrow
    全站熱搜

    lver76 發表在 痞客邦 留言(0) 人氣()