标签:style blog http io strong 数据 ar 2014 div
在我的项目中,为了在程序中统计两个进程传递消息的时间,所以需要linux的时间函数。
1 利用time和localtime获取本地事件(精确到s)
#include <time.h>
#include <stdio>
int main(int argc, char *argv[])
{
time_t now; //实例化time_t结构,time_t实际是一个long
struct tm *timenow;
time(&now); //time函数读取现在的时间(国际标准时间非北京时间),然后传值给now
timenow = localtime(&now); //localtime函数把从time取得的时间now换算成你电脑中的时间(就是你设置的地区)
int _sec = timenow->tm_sec;
int _min = timenow->tm_min;
int _hour = timenow->tm_hour;
int _day = timenow->tm_mday;
int _mon = timenow->tm_mon+1;
int _year = timenow->tm_year + 1900;
char ct0[30];
sprintf(ct0,"%4d%02d%02d %02d:%02d:%02d",_year,_mon,_day,_hour,_min,_sec);
printf("%s",ct0);
return 0;
}

其中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;不了解情况时,tm_isdst()为负。*/
};
2 利用mktime获得秒数
time_t mktime(struct tm * timeptr);
mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。
3 利用gettimeofday获取时间(精确到us)
int gettimeofday(struct timeval*tv, struct timezone *tz);
//保存时区结果
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST时间的修正方式*/
};
//保存获取时间结果
struct timeval{
long int tv_sec; //秒数
long int tv_usec; //微秒数
};
一个例子:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
struct timeval tv;
/*
//在我的机器上如果不加的话会报错
//ttime.c:13: error: storage size of ‘tz’ isn’t known
struct timezone{
int tz_minuteswest;
int tz_dsttime;
};
struct timezone tz;
*/
int main(int argc, char *argv[])
{
time_t now;
struct tm *timenow;
time(&now);
//gettimeofday(&tv,&tz);
gettimeofday(&tv,NULL);
printf("%d %d\n",now,tv.tv_sec);
printf("%d\n",tv.tv_usec);
timenow = localtime(&now);
int _usec = tv.tv_usec - (tv.tv_usec/1000)*1000;
int _msec = tv.tv_usec/1000;
int _sec = timenow->tm_sec;
int _min = timenow->tm_min;
int _hour = timenow->tm_hour;
int _day = timenow->tm_mday;
int _mon = timenow->tm_mon+1;
int _year = timenow->tm_year + 1900;
char ct0[30];
sprintf(ct0,"%4d%02d%02d %02d:%02d:%02d %d %d\n",_year,_mon,_day,_hour,_min,_sec,_msec,_usec);
printf("%s",ct0);
return 0;
}

标签:style blog http io strong 数据 ar 2014 div
原文地址:http://www.cnblogs.com/dy-techblog/p/3928926.html