Linux時間操作(time、gettimeofday)


一、time函數   

  1. #include <time.h>
  2. time_t time(time_t *calptr);

返回距計算機元年的秒數
一旦取得這種以秒計的很大的時間值后,通常要調用另一個時間函數將其變換為人們可讀的時間和日期

#include <time.h>    
//calendar time into a broken-down time expressed as UTC
struct tm *gmtime(const time_t *calptr);

//converts the calendar time to the local time, taking into account the local time zone and
//daylight saving time flag
struct tm *localtime(const time_t *calptr);

//converts it into a time_t value
time_t mktime(struct tm *tmptr);

  struct tm {        /* a broken-down time */
     int  tm_sec;     /* seconds after the minute: [0 - 60] */
     int  tm_min;     /* minutes after the hour: [0 - 59] */
     int  tm_hour;    /* hours after midnight: [0 - 23] */
     int  tm_mday;    /* day of the month: [1 - 31] */
     int  tm_mon;     /* months since January: [0 - 11] */
     int  tm_year;    /* years since 1900 */
     int  tm_wday;    /* days since Sunday: [0 - 6] */
     int  tm_yday;    /* days since January 1: [0 - 365] */
     int  tm_isdst;   /* daylight saving time flag: <0, 0, >0 */

  // 以下兩個字段在有些版本中是存在的,使用時需要查看對應的頭文件確認

  long int tm_gmtoff; /* Seconds east of UTC. */
  const char *tm_zone; /* Timezone abbreviation. */

   };  

  1. char *asctime(const struct tm *tmptr);
  2. char *ctime(const time_t *calptr);
  3. asctime()和ctime()函數產生形式的26字節字符串,這與date命令的系統默認輸出形式類似:
        Tue Feb 10 18:27:38 2004/n/0


二、gettimeofday函數得到更精確的時間

  1. #include <sys/time.h>
  2. int gettimeofday(struct timeval *restrict tp, void *restrict tzp);
  3. 第二個形參是基於平台實現的,使用的時候最好用NULL

struct timeval{
    time_t tv_sec;        /*** second ***/
    susecond_t tv_usec;    /*** microsecond 微妙***/
}

1秒=1000毫秒,
1毫秒=1000微秒,
1微妙=1000納秒,
1納秒=1000皮秒。
秒用s表現,毫秒用ms,微秒用μs表示,納秒用ns表示,皮秒用ps表示。

三、內核時間 

內核有兩個重要的全局變量:
unsigned long jiffies;
timeval xtime ;


jiffies 是記錄着從電腦開機到現在總共的"時鍾中斷"的次數。
文件linux-2.6.24/kernel/timer.c  
void do_timer(unsigned long ticks)
{
    jiffies_64 += ticks;
    update_times(ticks);
}


xtime 是從cmos電路或rtc芯片中取得的時間,一般是從某一歷史時刻開始到現在的時間。
這個就是所謂的"牆上時鍾walltimer",通過它可計算得出操作系統需要的日期時間,它的精確度是微秒。

xtime第一次賦值是在系統啟動時調用timekeeping_init或time_init進行的
再調用read_persistent_clock進一步調用get_rtc_time得到的

PS:在/proc/uptime里面的兩個數字分別表示:   
the uptime of the system(seconds),
and the amount of time spent in idle process(seconds). 

 

 注:

  今天寫一個時間管理模塊,updateTime(time)  time為year month day hour minute second minlliseconds任意一個,包括正數 負數

    其中一個約定為  1970年之后的時間管理。 主要通過閏年來管理日期。對某個量進行設置后,對應調整日期,比較麻煩。

     如果利用 系統的  mktime 和 localtime/gmtime  在 tm size_t 之間進行轉換,及其方便!  

 

 

 

 

 

 

 

參考:

http://blog.csdn.net/scottgly/article/details/6568513

 


免責聲明!

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



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