定時器 setitimer 和 gettimeofday 獲取當前時間【Linux微秒級】

setitimer延時、定時

#include <sys/time.h>
int setitimer(
  int which,
  const struct itimerval * new_value,
  struct itimerval * old_value
);

struct itimerval{
  struct timeval it_interval; //週期執行時間
  struct timeval it_value; //延遲執行時間
};

struct timeval{
  time_t tv_sec; //秒
  suseconds_t tv_usec; //微秒
};

參數

which :
  ITIMER_REAL:以系統真實的時間來計算,送出SIGALRM信號。  ITMER_VIRTUAL:以該進程在用戶態下花費的時間來計算,送出SIGVTALRM 信號。
  ITMER_PROF:以該進程在用戶態下和內核態下所費的時間來計算,送出SIGPROF信號。

old_value:
  一般置爲NULL,用來存儲上一次setitimer調用時設置的new_value。

返回值

  調用成功返回0,否則返回-1。

工作機制

it_value倒計時,爲0時觸發信號,it_value重置爲it_interval,繼續倒計時,週期執行。

週期執行時,it_value不爲0,設置it_interval;
延遲執行時,設置it_value,it_interval爲0。

例子

#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
void signalHandler(int signo){    
	switch (signo){        
	case SIGALRM:            
		printf("Caught the SIGALRM signal!\n");            
		break;  
	 }
 }
 //延時1微秒便觸發一次SIGALRM信號,以後每隔200毫秒觸發一次SIGALRM信號。
 int main(int argc, char *argv[]){    
	 //安裝SIGALRM信號    
	 signal(SIGALRM, signalHandler);    
	 struct itimerval new_value, old_value;    
	 new_value.it_value.tv_sec = 0;    
	 new_value.it_value.tv_usec = 1;    
	 new_value.it_interval.tv_sec = 0;   
	 new_value.it_interval.tv_usec = 200000;    
	 setitimer(ITIMER_REAL, &new_value, &old_value);    f
	 or(;;);    
	 return 0;
 }

SIGALRM信號

#include <signal.h>

在POSIX兼容平臺上,SIGALRM是在定時器終止時發送給進程的信號。
SIG是信號名的通用前綴。
ALRM是alarm的縮寫,即定時器。

要使用定時器,首先要安裝SIGALRM信號。如果不安裝,進程收到信號後,缺省的動作就是終止當前進程。

獲取系統當前時間

#include <sys/time.h>
#include <unistd.h>
int gettimeofday(
  struct timeval * tv,
  struct timezone * tz
);

struct timeval{
  long tv_sec; //秒
  long tv_usec; //微秒
};

struct timezone{
  int tz_minuteswest; //和格林威治時間差了多少分鐘
  int tz_dsttime; //日光節約時間的狀態
};

參數

tv:返回當前時間
tz:當地時區信息

返回值

  調用成功返回0,否則返回-1。

例子

#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main(){
	struct timeval tv;
	gettimeofday(&tv,NULL);
	printf("second:%ld\n",tv.tv_sec);//秒
	printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000);//毫秒
	printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
	sleep(3);
	std::cout << "3s later:" << std::endl;
	gettimeofday(&tv,NULL);printf("second:%ld\n",tv.tv_sec);//秒
	printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000);//毫秒
	printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
	return0;
}
//獲取當前時間,單位毫秒
int getCurrentTime(){     
	struct timeval tv;     
	gettimeofday(&tv,NULL);     
	return tv.tv_sec*1000 + tv.tv_usec/1000;
}

參考資料:
https://blog.csdn.net/lixianlin/article/details/25604779
https://blog.csdn.net/zaishaoyi/article/details/20239997
https://baike.baidu.com/item/SIGALRM/22777025
https://blog.csdn.net/xiewenhao12/article/details/78707101
http://c.biancheng.net/cpp/html/142.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章