Linux下clock_gettime函式詳解
要包含這標頭檔案<time.h>
且在編譯連結時需加上 -lrt ;因為在librt中實現了clock_gettime函式。
---
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC,ts);
printf("%d %d",ts.tv_sec, ts.tv_nsec);打印出來的時間跟 cat /proc/uptime第一個引數一樣
/proc/uptime裡面的兩個數字分別表示:
the uptime of the system (seconds), and the amount of time spent inidle process (seconds).
把第一個數讀出來,那就是從系統啟動至今的時間,單位是秒
Middleware對POSIX提供的標準計時器API進行封裝,主要提供了兩種型別的時鐘的封裝。一種是CLOCK_REALTIME,另一種是CLOCK_MONOTONIC。對與man手冊的解釋是:
CLOCK_REALTIME: Systemwide realtime clock. 系統範圍內的實時時鐘。
CLOCK_MONOTONIC:Represents monotonic time. Cannot be set.表示單調時間,不能被設定的。
手冊中解釋的比較籠統。我個人的理解是:
CLOCK_REALTIME:這種型別的時鐘可以反映wall clocktime,用的是絕對時間,當系統的時鐘源被改變,或者系統管理員重置了系統時間之後,這種型別的時鐘可以
得到相應的調整,也就是說,系統時間影響這種型別的timer。
CLOCK_MONOTONIC:用的是相對時間,他的時間是通過jiffies值來計算的。該時鐘不受系統時鐘源的影響,只受jiffies值的影響。
建議使用:
CLOCK_MONOTONIC這種時鐘更加穩定,不受系統時鐘的影響。如果想反映wall clocktime,就使用CLOCK_REALTIME。
clock_gettime比gettimeofday更加精確
clock_gettime( )提供了納秒的精確度,給程式計時可是不錯哦;
函式的原型如下:
int clock_gettime(clockid_t clk_id, struct timespect *tp);clockid_t clk_id用於指定計時時鐘的型別,對於我們Programmr以下三種比較常用:
CLOCK_REALTIME, a system-wide realtime clock. CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPUfor each process. CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPUfor each of the threads. CLOCK_REALTIME2time_t tv_sec; 3long tv_nsec; 4};
呵呵,好啦!該講的都剛清楚了,下面我們就上程式碼把;
程式碼 1 #include <iostream>2 #include <time.h>3 usingnamespace std;4 5 timespec diff(timespec start, timespec end);
6 7 intmain()
8 {
9 timespec time1, time2;
10int temp;
11clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
12for (inti = 0;i<242000000;i++)
13temp+=temp;
14clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
15cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
16return 0;
17}
1819timespec diff(timespec start, timespec end)
20{
21timespec temp;
22if ((end.tv_nsec-start.tv_nsec)<0){
23temp.tv_sec = end.tv_sec-start.tv_sec-1;
24temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
25} else {
26temp.tv_sec = end.tv_sec-start.tv_sec;
27temp.tv_nsec = end.tv_nsec-start.tv_nsec;
28}
29return temp;
30}