Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 使用 clock_gettime 函數獲取奈秒級精確時間測量程式效能

編輯:關於 Linux

程式效能分析常需奈秒級時間戳。Linux 用戶空間可用 clock_gettime 實現,精度遠高於 gettimeofday。

函數原型

long sys_clock_gettime(clockid_t which_clock, struct timespec *tp);

時鐘類型 (which_clock)

  • CLOCK_REALTIME:系統實時時間 (UTC 1970 起),受用戶修改系統時間影響。
  • CLOCK_MONOTONIC:單調時鐘,從開機起計,不受系統時間變更影響,適合測量間隔。
  • CLOCK_PROCESS_CPUTIME_ID:本進程 CPU 耗時。
  • CLOCK_THREAD_CPUTIME_ID:本線程 CPU 耗時。

timespec 結構

struct timespec {
  time_t tv_sec;   // 秒
  long   tv_nsec;  // 奈秒
};

完整測量範例

#include 
#include 
#include 

int main(void) {
  struct timespec time_start={0,0}, time_end={0,0};
  clock_gettime(CLOCK_REALTIME, &time_start);
  printf("start time %llus, %llu ns\n", time_start.tv_sec, time_start.tv_nsec);
  clock_gettime(CLOCK_REALTIME, &time_end);
  printf("end time %llus, %llu ns\n", time_end.tv_sec, time_end.tv_nsec);
  printf("duration: %llus %llu ns\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec);
  return 0;
}

編譯與結果

gcc test.c -o test -lrt
./test
# start time 1397395863s, 973618673 ns
# end time 1397395863s, 973633297 ns
# duration: 0s 14624 ns  (約 15 微秒,一次 printf 開銷)

連結時需加 -lrt (Real-Time library)。此法適合微基準測試與高精度計時需求。

Copyright © Windows教程網 All Rights Reserved