vol34. Linuxの時間関数

Linuxでは、time_t, tm, timespec, timevalなど、様々な型や構造体が、様々な関数で 使用されている。全体像を整理してみた。

全体像

f:id:john-rama01:20180602050949p:plain

man page で引くと
- gmtime() やlocaltime()は、ライブラリ関数
- time(), gettimeofday(), clock_gettime()はシステムコール

である

全体的にみると、システムコールカーネル層から取得した時刻を、ライブラリ関数で人
間にもわかりやすい形に加工するといった構造だ。

time_tは秒単位の情報を、timespec, timevalはそれぞれ、us, ns単位の情報を扱う。

    struct timeval {  
        time_t tv_sec;            /* Seconds.  */  
        suseconds_t tv_usec;      /* Microseconds.  */  
    };  

    struct timespec {  
        time_t tv_sec; /* Seconds.  */  
        long tv_nsec;  /* Nanoseconds.  */  
    };  

timeval時刻を取得するには、gettimeofday()を、timespec時刻を取得するには、
clock_gettime()を使う。ただし、gettimeofday()はPOSIX環境で古くから使われてきたが
、今は、非推奨でclock_gettimeが推奨されている。

time_t のインプリはアーキテクチャ依存で、32bit だったり、64bitの変数だったりする

time_tの情報を人間にわかりやすい形の情報で格納するための構造体がstruct tmだ。

    struct tm {  
        /*  
         * the number of seconds after the minute, normally in the range  
         * 0 to 59, but can be up to 60 to allow for leap seconds  
         */  
        int tm_sec;  
        /* the number of minutes after the hour, in the range 0 to 59*/  
        int tm_min;  
        /* the number of hours past midnight, in the range 0 to 23 */  
        int tm_hour;  
        /* the day of the month, in the range 1 to 31 */  
        int tm_mday;  
        /* the number of months since January, in the range 0 to 11 */  
        int tm_mon;  
        /* the number of years since 1900 */  
        long tm_year;  
        /* the number of days since Sunday, in the range 0 to 6 */  
        int tm_wday;  
        /* the number of days since January 1, in the range 0 to 365 */  
        int tm_yday;  
    };  

個々の関数の役割は、man page で確認して欲しい。

参照: