内核测量时间流逝的三种方式:
1 真实时间
2 进程时间
3 单调时间
时间的数据结构
1 原始的表示法
typedef long time_t
2 微妙精确度
#include <sys/time.h>
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
3 纳秒精确度
#include <time.h>
struct timespec {
time_t tv_sec;
long tv_nsec;
};
实际上后两种没有办法提供所述的精确度,因为系统定时器无法提供纳秒甚至微妙分辨率。
分解时间
c标准提供tm结构,在unix的时间和字符串时间之间进行转换。
#include <time.h>
struct tm{
int tm_sec;
...
};
posix时钟
CLOCK_MONOTONIC
CLOCK_PROCESS_CPUTIME_ID
CLOCK_REALTIME /*可一直的程序在这4中时钟源中应该使用此定时器*/
CLOCK_THREAD_CPUTIME_ID
取得当前时间
#include <time.h>
time_t time(time_t *t);
#include <sys/time.h>
int gettimeofday(structtimeval*tv, struct timezone *tz);
struct timezone 被废弃传NULL即可
#include <time.h>
int clock_gettime(clockid_t clock_id, /*指定时间来源, linux支持4种标准的时钟来源,*/
struct timespec *ts);
取得进程时间
#include <sys/times.h>
struct tms {
clock_t tms_utime; /*进程用户空间消费时间*/
clock_t tms_stime; /*进程内核空间消费时间*/
clock_t tms_cutime; /*子进程用户空间消费时间*/
clock_t tms_cstime;/*子进程内核空间消费时间*/
};
clock_t times (struct tms *buf);
此还是返回绝对时间,去两次调用的相对变化。
设定当前时间
#define _SVIF_SOURCE
#include <time.h>
int stime(time_t *t);
以微妙精确度是定时间
int settimeofday(const struct timeval *tv, const struct timezone timezone *tz);
正如clock_gettime改善了gettimeofday(), clock_settime()淘汰了setttimeofday()
#include <time.h>
int clock_settime(clockid_t clock_id, const struct timespec *ts);
操作时间
char *asctime()
char *asctime_t() 线程安全
time_t mktime(struct tm *tm);
char *ctime(const time_t *timep);
char *ctime_t(const time_t *timeep, char *buf)
struct tm* gmtime
struct rm *gmtime_r
struct rm *localtime
struct localtime_r
double difftime
休眠与等待
unsigned int sleep
int usleep
int nanosleep
POSIX提供的高级休眠
int clock_nanosleep
可移植的方式休眠
int select /*亚秒级*/
定时器
使用SIGALRM的定时器
unsigned int alarm(unsigned int second);
int getitimer
int setitimer
高级定时器
timer_create
timer_settime
timer_delete
int timer_gettime
转载于:https://blog.51cto.com/baigoogledu/396292