#定时器
struct itimerval {
struct timeval it_interval; //计时器重启动的间歇值
struct timeval it_value; //计时器安装后首先启动的初始值
};
struct timeval {
long tv_sec; //秒
long tv_usec; // 微妙(1/1000000)
};
struct timespec {
time_t tv_sec; //秒
long tv_nsec; // nanoseconds 纳秒
};
1,000 皮秒 = 1纳秒
1,000,000 皮秒 = 1微秒
1,000,000,000 皮秒 = 1毫秒
1,000,000,000,000 皮秒 = 1秒
###time_t time(time_t * seconds)
函数返回从TC1970-1-1 0:0:0开始到现在的秒数 如果 seconds 不为空,则返回值也存储在变量 seconds 中。
###unsigned int alarm(unsigned int seconds);
seconds:指定秒数
向系统发送SIGALRM信号
函数返回值:
成功:如果调用此alarm()前,进程已经设置了闹钟时间,则返回上一个闹钟时间的剩余时间,否则返回0。
出错:-1
###extern __usconds_t ualarm(__useconds_t __value, __useconds_t __interval);
在使当前进程在指定时间(第一个参数)内产生SIGALRM信号,然后每隔指定时间(第二个参数)重复产生SIGALRM信号。
###int setitimer(int which, const struct itimerval *new_value,struct itimerval *old_value);
###int getitimer(int which, struct itimerval *value);
用来实现延时和定时的功能
which参数表示类型,可选的值有:
ITIMER_REAL: 以系统真实的时间来计算, 送出SIGALRM信号。
ITIMER_VIRTUAL: 以该进程在用户态下花费的时间来计算, 送出SIGVTALRM信号。
ITIMER_PROF: 以该进程在用户态下和内核态下所费的时间来计算, 送出SIGPROF信号。
new_value 用来对计时器进行设置
old_value 通常用不上,设置为NULL,它是用来存储上一次setitimer调用时设置的new_value值。
###int clock_gettime(clockid_t clk_id,struct timespec *tp);
clk_id : 检索和设置的clk_id指定的时钟时间。
CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变
CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
##代码比较
1 #include<stdio.h>
2 #include<time.h>
3 #include<sys/time.h>
4
5 void nowtime_ns()
6 {
7 printf("---------------------------struct timespec---------------------------------------\n");
8 printf("[time(NULL)] : %ld\n", time(NULL));
9 struct timespec ts;
10 clock_gettime(CLOCK_REALTIME, &ts);
11 printf("clock_gettime : tv_sec=%ld, tv_nsec=%ld\n", ts.tv_sec, ts.tv_nsec);
12
13 struct tm t;
14 char date_time[64];
15 strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&ts.tv_sec, &t));
16 printf("clock_gettime : date_time=%s, tv_nsec=%ld\n", date_time, ts.tv_nsec);
17 }
18 void nowtime_us()
19 {
20 printf("---------------------------struct timeval----------------------------------------\n");
21 printf("[time(NULL)] : %ld\n", time(NULL));
22 struct timeval us;
23 gettimeofday(&us,NULL);
24 printf("gettimeofday: tv_sec=%ld, tv_usec=%ld\n", us.tv_sec, us.tv_usec);
25
26 struct tm t;
27 char date_time[64];
28 strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&us.tv_sec, &t));
29 printf("gettimeofday: date_time=%s, tv_usec=%ld\n", date_time, us.tv_usec);
30 }
31
32 int main(int argc, char* argv[])
33 {
34 nowtime_ns();
35 printf("\n");
36 nowtime_us();
37 printf("\n");
38 return 0;
39 }