Linux: Linux C 獲取當前系統時間的時間戳(精確到秒、毫秒、微秒) gettimeofday


說明

獲取當前的時間的秒數和微秒數本方法需要用到 gettimeofday() 函數,該函數需要引入的頭文件是  <sys/time.h>  。

函數說明 int gettimeofday (struct timeval * tv, struct timezone * tz)

1、返回值:該函數成功時返回0,失敗時返回-1 
2、參數 
struct timeval{ 
  long tv_sec; //
  long tv_usec; //微秒 
}; 
struct timezone 
{ 
  int tz_minuteswest; //和Greenwich 時間差了多少分鍾 
  int tz_dsttime; //日光節約時間的狀態 
}; 

示例

#include <sys/time.h>
#include <stdio.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); // 讓程序休眠3秒
    printf("---------------------sleep 3 second-------------------\n");
    
    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); // 徽秒

    return 0;
}

運行結果:

second: 1554963664
millisecond: 1554963664748
microsecond: 1554963664748007
---------------------sleep 3 second-------------------
second: 1554963667
millisecond: 1554963667748
microsecond: 1554963667748621

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM