时间编程
时间类型
(1)Coordinated Universal Tine(UTC):世界标准时间(即格林威治标准时间,Greenwich
Mean Time,GMT)
(2)Calendar Time:日历时间,是用“从一个标准时间点(如:1970年1月1日0点)到此时经过的秒数”来表示的时间。
时间获取
#include
<time.h>
time_t time(time_t *tloc)
功能:获取日历时间,即从1970年1月1日0点到现在所经历的秒数。
/*typedef long time_t*/
时间转化:
(1)
struct tm *gmtime(const time_t *timep)
功能:将日历时间转化为格林威治标准时间,并保存至TM结构。
(2)
struct tm *localtimg(const time_t *timep)
功能:将日历时间转化为本地时间,并保存在TM结构。
时间保存:
struct
tm
{
int tm_sec; //秒值
int tm_min; //分钟值
int tm_hour; //小时值
int tm_mday; //本月第几日
int tm_mon; //本年第几月
int tm_year; //tm_year + 1900=那一年
int tm_wday; //本周第几日
int tm_yday; //本年第几日
int tm_isdst; //日光节约时间
#include <time.h>
#include <stdio.h>
int main(void)
{
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);
}
时间显示:
(1)
char *asctime(const struct tm *tm)
功能:将TM格式的时间转化为字符串,如:
Sat
Jul 30 08:43:03 2005
(2)
char *ctime(const time_t *timep)
功能:将日历时间转化为本地时间的字符串形式。
注意:第一种方法用三步:①获取日历时间;②把日历时间转化为tm格式时间③将tm格式时间转化为字符串
而第二种方法只用两步:①获取日历时间;②把日历时间转化为本地时间的字符串形式
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm *ptr;
time_t lt;
/*获取日历时间*/
lt=time(NULL);
/*转化为格林威治时间*/
ptr=gmtime(lt);
/*以格林威治时间的字符串方式打印*/
printf(asctime(ptr));
/*以本地时间的字符串方式打印*/
printf(ctime(<));
return 0;
}
获取时间:
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<100000;i++)
for(j=0;j<1000;j++)
y++;
}
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);
exit(0);
}
#include <time.h>
#include <stdio.h>
int
main(void)
{
struct tm *ptr;
time_t lt;
lt=time(NULL);
ptr=gmtime(<);
printf(asctime(ptr));
printf(ctime(<));
return 0;
}
延迟执行:
(1)
unsigned int sleep(unsigned int seconds)
功能:使程序睡眠seconds秒
(2)
void usleep (unsigned long usec)
功能:使程序睡眠usec微秒