时间编程:
日历时间获取:
time_t time(time_t *tloc)
功能:获取日历时间,即从1970年1月1日0点到所经历的秒数。
/*typedef long time_t */
Example:
#include <stdio.h>
#include <time.h>
int main(){
time_t lt;
lt = time(NULL); //得到日历时间
printf("time is %ld\n", lt);
return 0;
}
tm 结构体数据结构:
struct tm{
int tm_sec; //秒值
int tm_min; //分钟值
int tm_hour; //小时值
int tm_mday; //本月第几日
int tm_mon; //本月第几月
int tm_year; //tm_year + 1900为实际的年份,如现在是2012,返回为112
int tm_wday; //本周第几日
int tm_yday; //本年第几日
int tm_isdst; //日光节约时间
}
获取时间example:
#include <stdio.h>
#include <time.h>
int main(){
struct tm *local ; //定义tm结构体
struct tm *gm;
time_t t;
t = time(NULL); //获取日历时间
local = localtime(&t); //得到本地时间
printf("The local minute is: %d\n", local->tm_min);
printf("The local hour is: %d\n", local->tm_hour);
printf("The local month is: %d\n", local->tm_mon);
printf("The local year is: %d\n", local->tm_year+1900);
printf("The local wday is: %d\n", local->tm_wday);
printf("\n\n\n");
gm = gmtime(&t); //得到格林威治时间
printf("The gm minute is: %d\n", gm->tm_min);
printf("The gm hour is: %d\n", gm->tm_hour);
printf("The gm month is: %d\n", gm->tm_mon);
printf("The gm year is: %d\n", gm->tm_year+1900);
printf("The gm wday is: %d\n", gm->tm_wday); return 0;
}
时间显示:
#include <stdio.h>
#include <time.h>
int main(){
struct tm *lt;
time_t t;
t = time(NULL); //获取日历时间
lt = gmtime(&t); //获取格林威治时间
printf(asctime(lt)); //格式化格林威治时间字符串输出,例如:"Tue May 21 13:46:22 1991\n"
printf(ctime(&t)); //类似于asctime,实现本地时间格式化,本地时间字符串形式
return 0;
}
获取时间:gettimeofday
int gettimeofday(struct timeval *tv, struct timezone *tz)
功能:获取距离今天凌晨到现在的时间差,常用于事件耗时。
结构体timeval:
Struct timeval{
long int tv_sec; //秒数
long int tv_usec; //微妙数
}
示例:实现计算函数执行时间
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
#include <math.h>
int main(){
struct timeval tv_start, tv_end; //定义两个timeval结构体
gettimeofday(&tv_start, NULL); //获取函数执行前的 timeval时间
func(); //执行函数
gettimeofday(&tv_end, NULL); //获取函数执行完的timeval时间
float timeuse;
timeuse = 1000000 * (tv_end.tv_sec - tv_start.tv_sec) + (tv_end.tv_usec - tv_start.tv_usec);
timeuse = timeuse/1000000; //计算执行时间
printf("The total time is: %f\n", timeuse);
exit(0);
}
func(){
int i;
long sum;
for(i=1; i < 1000000; i++){
sum += i;
}
}
使程序睡眠指定时间
unsigned int sleep(unsigned int second)
功能:使程序睡眠seconds秒
void usleep(unsigned long usec)
功能:使程序睡眠usec微妙
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
int main(){
struct timeval tv_start, tv_end;
gettimeofday(&tv_start, NULL);
sleep(5); //休眠5s
usleep(10000000); //休眠10000000 usec(10s)
gettimeofday(&tv_end, NULL);
float timeuse;
timeuse = 1000000 * (tv_end.tv_sec - tv_start.tv_sec) + (tv_end.tv_usec - tv_start.tv_usec);
timeuse = timeuse/1000000;
printf("The total time is: %f\n", timeuse);
exit(0);
}