應用程序設計-時間

內核測量時間流逝的三種方式:

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

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章