工作中经常要用到时间编程相关的函数,发现都忘记了回头看了下视频整理些笔记。都是很基础的函数。
时间类型
1.UTC:世界标准时间,格林威治标准时间(GMT)。
2.Calendar Time:日历时间,是用“从一个标志时间点(如:1870年1月1日0点)到此时经过的秒数”来表示的时间。
常用函数
1.获取日历时间
#include <time.h>
/*typedef long time_t */
time_t time(time_t *tloc)
功能:获取日历时间,即从1970年1月1日0点到现在所经历的秒数。
2.时间转化
struct tm* gmtime(const time_t *timep)
功能:将日历时间转化为格林威治标准时间,并保存到到TM结构。
struct tm* localtime(const time_t *timep)
功能:将日历时间转化为本地时间,并保存到到TM结构。
3.时间保存
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;不了解情况时,tm_isdst()为负。*/
long int tm_gmtoff; /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/
const char *tm_zone; /*当前时区的名字(与环境变量TZ有关)*/
};
程序例子
#include <time.h>
#include <stdio.h>
int main()
{
struct tm *local;
time_t t;
t=time(NULL);
local=localtime(&t);
printf("Local hour is:%d\n",local->tm_hour);
local=gmtime(&t);
printf("UTC hour is:%d\n",local->tm_hour);
return 0;
}
运行结果:
time(NULL); // 获取本地时间
注意:tm_year是相对值,从1900开始算的,tm_year + 1900 = 哪一年
4.时间显示
函数:char * asctime(const struct tm *tm)
功能:将tm格式的时间转化为字符串,如Sat Jul 30 08:45:03:2014
函数:char *ctime(const time_t *timep)
功能:将日历时间转化为本地时间的字符串形式。
#include <time.h>
#include <stdio.h>
int main()
{
struct tm *ptr;
time_t lt;
lt=time(NULL); //获取日历时间
ptr=gmtime(<);//获取格林威治时间
printf(asctime(ptr));
printf(ctime(<));
return 0;
}
运行结果
5.获取时间
函数:int gettimeofday(struct timeval *tv,struct timezone *tz)
功能:获取从今日冷晨到现在的时间差,常用于计算事件耗时。
struct timeval{
int tv_sec;//秒数
int tv_usec;//微秒数
}
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void function()
{
unsigned int i,j;
double y;
for (i = 0; i < 1000 ;i++)
{
for (j = 0 ; j < 1000; i++)
{
y++;
}
}
}
int main()
{
struct timeval tpstart,tpend;
float timeuse;
gettimeofday(&tpstart,NULL);//开始时间
function();
gettimeofday(&tpend,NULL); //结束时间
//计算执行时间
timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) +
tpend.tv_usec - tpstart.tv_usec;
timeuse /= 1000000;
printf("used time = %f\n",timeuse);
return 0;
}
6.延时执行
函数:unsigned int sleep(unsigned int seconds)
功能:使程序睡眠seconds秒。
函数:void usleep(unsigned long usec)
功能:使程序睡眠usec微妙。