CLOCK_MONOTONIC 与 CLOCK_REALTIME 区别

Clock_realtime 

代表机器上可以理解为当前的我们所常看的时间,其当time-of-day 被修改的时候而改变,这包括NTP对它的修改(NTP:Network Time Protocol(NTP)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间校正(LAN上与标准间差小于1毫秒,WAN上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。)
CLOCK_MONOTONIC 
代表从过去某个固定的时间点开始的绝对的逝去时间,它不受任何系统time-of-day时钟修改的影响,如果你想计算出在一台计算机上不受重启的影响,两个事件发生的间隔时间的话,那么它将是最好的选择。

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_MONOTONIC
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用来存储当前的时间,其结构如下:
   
   
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
 代码
 #include <iostream>
 #include <time.h>
  using namespace std;
  
 timespec diff(timespec start, timespec end);
  
  int main()
 {
     timespec time1, time2;
     int temp;
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
     for (int i = 0; i< 242000000; i++)
         temp+=temp;
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
     cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
     return 0;
 }
  
 timespec diff(timespec start, timespec end)
 {
     timespec temp;
     if ((end.tv_nsec-start.tv_nsec)<0) {
         temp.tv_sec = end.tv_sec-start.tv_sec-1;
         temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
     } else {
         temp.tv_sec = end.tv_sec-start.tv_sec;
         temp.tv_nsec = end.tv_nsec-start.tv_nsec;
     }
     return temp;
 }
 

猜你喜欢

转载自igaozh.iteye.com/blog/1675767