今天发现一篇非常好的博文,是讲time()和gettimeofday()的。
网址如下http://blog.csdn.net/scottgly/article/details/6568513
在哥们的基础上,我做了一下修改,内容如下
一、time函数
- #include <time.h>
- time_t time(time_t *calptr);
返回距计算机元年的秒数
一旦取得这种以秒计的很大的时间值后,通常要调用另一个时间函数将其变换为人们可读的时间和日期
#include <time.h>
//calendar time into a broken-down time expressed as UTC
struct tm *gmtime(const time_t *calptr);
//converts the calendar time to the local time, taking into account the local time zone and
//daylight saving time flag
struct tm *localtime(const time_t *calptr);
//converts it into a time_t value
time_t mktime(struct tm *tmptr);
struct tm { /* a broken-down time */
int tm_sec; /* seconds after the minute: [0 - 60] */
int tm_min; /* minutes after the hour: [0 - 59] */
int tm_hour; /* hours after midnight: [0 - 23] */
int tm_mday; /* day of the month: [1 - 31] */
int tm_mon; /* months since January: [0 - 11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday: [0 - 6] */
int tm_yday; /* days since January 1: [0 - 365] */
int tm_isdst; /* daylight saving time flag: <0, 0, >0 */
};
- char *asctime(const struct tm *tmptr);
- char *ctime(const time_t *calptr);
- asctime()和ctime()函数产生形式的26字节字符串,这与date命令的系统默认输出形式类似:
Tue Feb 10 18:27:38 2004/n/0 - 其实只需要time()和localtime()即可。ctime()和astime()产生的串并不是我们所习惯的,所以可以自己写一个类似ctime()一样的函数,下面是我的代码,大家可以参考,最后输出结果是2012-06-14 17:19这样的字符串,是不是看起来非常顺眼啊。
#include <stdio.h> #include <time.h> #include <sys/time.h> int main(int argc,char **argv) { time_t now; struct timeval now_val; time(&now); struct tm gtime; gtime=(*localtime(&now)); gettimeofday(&now_val,NULL); printf("%4d-%02d-%02d %02d:%02d:%02d \n",1900+gtime.tm_year,1+gtime.tm_mon,gtime.tm_mday,gtime.tm_hour,gtime.tm_min,gtime.tm_sec); }
- #include <sys/time.h>
- int gettimeofday(struct timeval *restrict tp, void *restrict tzp);
- 第二个形参是基于平台实现的,使用的时候最好用NULL
struct timeval{
time_t tv_sec; /*** second ***/
susecond_t tv_usec; /*** microsecond 微妙***/
}
1秒=1000毫秒,
1毫秒=1000微秒,
1微妙=1000纳秒,
1纳秒=1000皮秒。
秒用s表现,毫秒用ms,微秒用μs表示,纳秒用ns表示,皮秒用ps表示。
时间比较准
三、总结
time()和gettimeofday()调用比较占用系统资源,所以不如对时间精度要求不高的情况下,尽量减少调用次数。笔者有次程序出现严重效率问题,最后调试和几天最后定为到了time()这个系统调用上。