Linux常用的時間函式&結構

include #<sys/time.h>

struct time_t{
   unsigned char tv_sec;  
   unsigned char tv_usec;
};

struct timeval {
    int tv_sec;
    int tv_usec;
};

struct tm
{
    int tm_sec;
    int tm_min;
    int tm_hour;
    int tm_mday;
    int tm_mon;
    int tm_year;
    int tm_wday;
    int tm_yday;
    int tm_isdst;
};

struct timeb {
  time_t         time;     // seconds since 00:00:00 GMT 1/1/1970
  unsigned short millitm; // milliseconds
  short          timezone;// difference between GMT and local,  * minutes
  short          dstflag;  // set if daylight savings time in affect
};

int ftime(struct timeb *buf);
取得目前時間


int gettimeofday(struct timeval *tp, void *tzp);
取得目前時間

struct tm * gmtime(const time_t * t);
轉換成格林威治時間。有時稱為GMT或UTC。

struct tm * localtime(const time_t *t);
轉換成本地時間。它可以透過修改TZ環境變數來在一台機器中,不同使用者表示不同時間。

time_t mktime(struct tm *tp);
轉換tm成為time_t格式,使用本地時間。

tme_t timegm(strut tm *tp);
轉換tm成為time_t格式,使用UTC時間。

double difftime(time_t t2,time_t t1);
計算秒差。


void timeradd(struct timeval *a, struct timeval *b,
              struct timeval *res);

void timersub(struct timeval *a, struct timeval *b,
              struct timeval *res);

void timerclear(struct timeval *tvp);

void timerisset(struct timeval *tvp);

void timercmp(struct timeval *a, struct timeval *b, CMP);

自己寫的timeval加減函數 因為有平台不支援上面的function
void timevalAdd(struct timeval* fA, struct timeval* fB, struct timeval* fResult)    {
    fResult->tv_sec = fA->tv_sec + fB->tv_sec;
    fResult->tv_usec = fA->tv_usec + fB->tv_usec;
    if (fResult->tv_usec >= 1000000)
    {
        fResult->tv_sec = fResult->tv_sec + 1;
        fResult->tv_usec -= 1000000;
    }
}
 
void timevalSub(struct timeval* fA, struct timeval* fB, struct timeval* fResult){
    fResult->tv_sec = fA->tv_sec - fB->tv_sec;
    fResult->tv_usec = fA->tv_usec - fB->tv_usec;
    if (fResult->tv_usec < 0) {
      fResult->tv_sec = fResult->tv_sec - 1;
      fResult->tv_usec += 1000000;
    }
}

轉錄自:http://eagerhsu.blogspot.tw/2010_10_01_archive.html

留言

Translate