http://blog.csdn.net/shanglihong/article/details/6562869
long sys_clock_gettime (clockid_t which_clock, struct timespec *tp);
which_clock參數解釋
CLOCK_REALTIME:系統即時時間,隨系統即時時間改變而改變,即從UTC1970-1-1 0:0:0開始計時,中間時刻如果系統時間被使用者該成其他,則對應的時間相應改變
CLOCK_MONOTONIC:從系統啟動這一刻起開始計時,不受系統時間被使用者改變的影響
CLOCK_PROCESS_CPUTIME_ID:本進程到當前代碼系統CPU花費的時間
CLOCK_THREAD_CPUTIME_ID:本線程到當前代碼系統CPU花費的時間
結構體的結構:
- struct timespec {
- time_t tv_sec; /* seconds */
- long tv_nsec; /* nanoseconds */
- };
//test9.c
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec time1 = {0, 0};
clock_gettime(CLOCK_REALTIME, &time1);
printf("CLOCK_REALTIME: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &time1);
printf("CLOCK_MONOTONIC: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
printf("CLOCK_PROCESS_CPUTIME_ID: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time1);
printf("CLOCK_THREAD_CPUTIME_ID: %d, %d", time1.tv_sec, time1.tv_nsec);
printf("/n%d/n", time(NULL));
sleep(1);
}
如果無法編譯,預設沒有加入該庫,請用gcc test9.c -lrt運行
在引入的librt.so 的路徑:{/usr/lib/x86_64-linux-gnu}
測試 #time ./a.out
http://www.cnblogs.com/daqiwancheng/archive/2010/07/01/1769522.html
Linux下使用clock_gettime給程式計時
哦,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 CPU for each process.CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.
CLOCK_REALTIME, a system-wide realtime clock.CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.struct timespect *tp用來儲存當前的時間,其結構如下:1 struct timespec {
2 time_t tv_sec; /* seconds */
3 long tv_nsec; /* nanoseconds */
4 };
呵呵,好啦!該講的都剛清楚了,下面我們就上代碼把;
代碼
1 #include <iostream>
2 #include <time.h>
3 usingnamespace std;
4
5 timespec diff(timespec start, timespec end);
6
7 int main()
8 {
9 timespec time1, time2;
10 int temp;
11 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
12 for (int i =0; i<242000000; i++)
13 temp+=temp;
14 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
15 cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
16 return0;
17 }
18
19 timespec diff(timespec start, timespec end)
20 {
21 timespec temp;
22 if ((end.tv_nsec-start.tv_nsec)<0) {
23 temp.tv_sec = end.tv_sec-start.tv_sec-1;
24 temp.tv_nsec =1000000000+end.tv_nsec-start.tv_nsec;
25 } else {
26 temp.tv_sec = end.tv_sec-start.tv_sec;
27 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
28 }
29 return temp;
30 }