1. 内核提供三种不同的方式来记录时间:
typedef long time_t;
#include <sys/time.h> struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ };
纳秒级精度表示: #include <time.h> struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
3. 获取当前时间
#include <time.h>
time_t time (time_t *t);
time() returns the current time represented as the number of seconds elapsed since the epoch
#include <sys/time.h> int gettimeofday (struct timeval *tv, struct timezone *tz);
struct timeval tv; int ret; ret = gettimeofday (&tv, NULL); if (ret) perror ("gettimeofday"); else printf ("seconds=%ld useconds=%ld\n", (long) tv.sec, (long) tv.tv_usec);
#include <sys/times.h> struct tms { clock_t tms_utime; /* user time consumed */ clock_t tms_stime; /* system time consumed */ clock_t tms_cutime; /* user time consumed by children */ clock_t tms_cstime; /* system time consumed by children */ }; clock_t times (struct tms *buf);
#include <time.h> int stime (time_t *t); #include <sys/time.h> int settimeofday (const struct timeval *tv, const struct timezone *tz);
参数tz总是为NULL
struct timeval tv = { 31415926, 27182818 }; int ret; ret = settimeofday (&tv, NULL); if (ret) perror ("settimeofday");
/* puts the invoking process to sleep for the number of seconds */ #include <unistd.h> unsigned int sleep (unsigned int seconds);
/* usleep() puts the invoking process to sleep for usec microseconds */ #define _XOPEN_SOURCE 500 #include <unistd.h> int usleep (unsigned int usec);
#include <sys/select.h> int select (int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
select函数将参数n设为0,三个检测事件集合全设为NULL,这时select就等同于一个精确时间的休眠函数,而且这种用法最具有可移植性
struct timeval tv = { .tv_sec = 0, .tv_usec = 757 }; select (0, NULL, NULL, NULL, &tv);
#include <unistd.h> unsigned int alarm (unsigned int seconds);
schedules the delivery of a SIGALRM signal to the invoking process after seconds of real time have elapsed
void alarm_handler (int signum) { printf ("Five seconds passed!\n"); } void func (void) { signal (SIGALRM, alarm_handler); alarm (5); pause (); }
间隔定时器:
#include <sys/time.h> int getitimer (int which, struct itimerval *value); int setitimer (int which, const struct itimerval *value, struct itimerval *ovalue); struct itimerval { struct timeval it_interval; /* next value */ struct timeval it_value; /* current value */ }; struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ };
void alarm_handler (int signo) { printf ("Timer hit!\n"); } void foo (void) { struct itimerval delay; int ret; signal (SIGALRM, alarm_handler); delay.it_value.tv_sec = 5; delay.it_value.tv_usec = 0; delay.it_interval.tv_sec = 1; delay.it_interval.tv_usec = 0; ret = setitimer (ITIMER_REAL, &delay, NULL); if (ret) { perror ("setitimer"); return; } pause (); }
Linux System Programming 学习笔记(十一) 时间,布布扣,bubuko.com
Linux System Programming 学习笔记(十一) 时间
原文:http://www.cnblogs.com/wwwjieo0/p/3760781.html