首页 > 代码库 > gettimeofday

gettimeofday

  调用gettimeofday()函数可以获取当前的格林尼治时间和当前时区。它的函数原型是:

int gettimeofday(struct timeval *restrict tp, void *restrict tzp);

  gettimeofday的参数涉及两个结构体:

struct timeval{
       time_t           tv_sec;      //秒(从1970.1.1)
       suseconds_t      tv_usec;     //微秒
};
struct timezone{
       int     tz_minuteswest;
       int     tz_dsttime;
};

  假设现在需要使用pthread_cond_timewait来阻塞一个线程,使用方法如下:

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t  lock = PTHREAD_MUTEAX_INITIALIZER;

struct timespec timeout;
get_timespec(&timeout, 500);
pthread_cond_timewait(&cond, &lock, &timeout);


void get_timespec(timespec *ts, int millisecond)
{
       struct timeval now;
       gettimeofday(&now,NULL);
       ts->tv_sec = now.tv_sec;
       ts->tv_nsec = now.tv_usec*1000;
       ts->tv_nsec += millisecond*1000;
}

 

gettimeofday