函数: time 头文件: time.h 函数原型: time_t time(time_t *timer) 获取当前的系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示从CUT(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。然后调用localtime将time_t所表示的CUT时间转换为本地时间(我们是+8区,比CUT多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。
struct tm *localtime(const time_t *clock);
localtime返回类型为struct tm类型的指针,如下为struct tm的结构体,分别为时、分、秒、日、月、年、等
struct tm { int tm_sec; /* 秒 – 取值区间为[0,59] */ int tm_min; /* 分 - 取值区间为[0,59] */ int tm_hour; /* 时 - 取值区间为[0,23] */ int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */ int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */ int tm_year; /* 年份,其值等于实际年份减去1900 */ int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */ int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */ int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时, }
接下来干货代码分析:
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { time_t cur_time; struct tm *local_time; //get current time; cur_time = time(NULL); local_time = localtime(&cur_time); printf("current time: Hour = %d Min = %d Sec = %d\n",local_time->tm_hour,local_time->tm_min,local_time->tm_sec); exit(0); }
Linux下通过gettimeofday()获取系统当前的时间及地区信息,其中时间可以达到微秒级;
头文件:#include<sys/time.h> 函数原型:int gettimeofday(struct timeval*tv,struct timezone *tz ) 其中struct timeval获取时间的结构体,struct timezone为获取时区信息结构体:
struct timeval{ long tv_sec; long tv_usec; } struct timezone{ int tz_minuteswest; //和greenwich时间差了多少分钟 int tz_dsttime; } 而settimeofday()函数是设置当前的时间和地区,其函数如下所示
头文件:#include<sys/time.h> 函数原型:int settimeofday(struct timeval *tv,struct timezone *tz) settimeofday()会把目前时间设成由tv所指的结构信息,当地时区信息则设成tz所指的结构;
#include<stdlib.h> #include<stdio.h> #include<sys/time.h> int main() { struct timeval curtime; struct timezone curzone; gettimeofday(&curtime,&curzone); printf("current time of sec is %ld, usec is %ld\n",curtime.tv_sec,curtime.tv_usec); printf("current zone is %d, dsttime is %d\n",curzone.tz_minuteswest,curzone.tz_dsttime); //settimeofday curtime.tv_sec +=60; settimeofday(&curtime,&curzone); printf("after settimeofday\n"); printf("current time of sec is %ld, usec is %ld\n",curtime.tv_sec,curtime.tv_usec); printf("current zone is %d, dsttime is %d\n",curzone.tz_minuteswest,curzone.tz_dsttime); return 0; }
(1)通过select设置定时器
#include <sys/time.h> #include <sys/select.h> #include <time.h> #include <stdio.h> void setTimer(int seconds, int mseconds) { struct timeval temp; temp.tv_sec = seconds; temp.tv_usec = mseconds; select(0, NULL, NULL, NULL, &temp); printf("Hello World\n"); return ; } int main() { int i; for(i = 0 ; i < 100; i++) setTimer(10, 0); return 0; } (2)通过SIGALRM+alarm设置定时器,然而其只能达到秒级别 #include<stdio.h> #include<signal.h> void timer(int signal) { if(signal == SIGALRM) { printf("HelloWorld\n"); alarm(1); } return ; } int main() { signal(SIGALRM,timer); alarm(1); getchar(); return 0; }