Linux时间编程
定义/功能:
日历时间(Calendar Time):用“一个标准时间(1970年1月1日0点)到此时经过的秒数”来表示时间。
格林威治时间Coordinatd Universal Time(UTC):世界标准时间,也就是大家所熟知的格林威治标准时间(Greenwich Mean Time,GMT)。
1. 获取日历时间
1.1 函数名(功能+UNIX环境高级编程手册)
time
1.2 函数原形(终端man命令:man 2 time)
time_t time(time_t *t );
1.3 函数功能
返回日历时间
1.4 所属头文件
#include <time.h>
1.5 返回值
成功:返回日历时间;失败:-1
1.6 参数说明
t:不为空时保存返回时间,为NULL时则无效
2. 获取格林威治时间
1.1 函数名(功能+UNIX环境高级编程手册)
gmtime
1.2 函数原形(终端man命令:man gmtime)
struct tm*gmtime(const time_t *timep );
1.3 函数功能
将参数timep所指向的日历时间转化为格林威治时间(世界标准时间)
1.4 所属头文件
#include <time.h>
1.5 返回值
成功:世界标准时间,以struct tm形式存储
失败:-1
2.6 参数说明
timep:带转化的日历时间
3. 获取本地时间
1.1 函数名(功能+UNIX环境高级编程手册)
localtime
1.2 函数原形(终端man命令:man localtime)
struct tm*localtime(const time_t *timep );
1.3 函数功能
将参数timep所指向的日历时间转化为用户所在的本地时间
1.4 所属头文件
#include <time.h>
1.5 返回值
成功:本地时间,以struct tm形式存储
失败:-1
3.6 参数说明
timep:带转化的日历时间
4. 字符串打印时间
1.1 函数名(功能+UNIX环境高级编程手册)
asctime
1.2 函数原形(终端man命令:man asctime)
char asctime(const struct tm tm);
1.3 函数功能
将tm结构体格式的时间转化为字符串
1.4 所属头文件
#include <time.h>
1.5 返回值
成功:本地时间,以struct tm形式存储
失败:-1
4.6 参数说明
tm:待转化的tm结构体时间
- 获取高精度时间
1.1 函数名(功能+UNIX环境高级编程手册)
gettimeofday
1.2 函数原形(终端man命令:man gettimeofday)
Int gettimeofday(struct timeval *tv, struct timezone *tz );
1.3 函数功能
获取高精度的时间
1.4 所属头文件
#include <sys/time.h>
1.5 返回值
成功:0
失败:-1
5.6 参数说明
tv:保存日历时间的秒数和微秒数
tz :时区代号,通常设置为空:NULL
综合实例代码:
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
void mytest(void)
{
int i,j;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++);
}
int main()
{
time_t ctime;
struct tm *tm;
struct tm *localtm;
char *chartm;
struct timeval tv;
int starttime=0;
int endtime = 0;
/*get calendar time*/
ctime = time(NULL);
printf("calendar time is %d\n",ctime);
/*turn calendar time to Greenwich Mean Time */
tm = gmtime(&ctime);
printf("UTC time: %d:%d\n",tm->tm_hour,tm->tm_min);
/*turn calendar time to local time */
localtm = localtime(&ctime);
printf("LCT time: %d:%d\n",localtm->tm_hour,localtm->tm_min);
/*print the time by str*/
chartm = asctime(localtm);
printf("LCT:%s\n",chartm);
/*get high accuracy time*/
gettimeofday(&tv, NULL);
starttime = tv.tv_sec*1000 + tv.tv_usec;
mytest();
gettimeofday(&tv, NULL);
endtime = tv.tv_sec*1000 + tv.tv_usec;
printf("run time is %d\n",endtime-starttime);
}