c语言时间设置函数.docxVIP

  • 7
  • 0
  • 约6.3千字
  • 约 8页
  • 2017-01-06 发布于贵州
  • 举报
c语言时间设置函数c语言时间设置函数

一、tm结构在time.h中的定义如下:#ifndef _TM_DEFINEDstruct 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()为负。*/ };#define _TM_DEFINED#endif二、time函数1、计时:clock()Clock_t clock(void);在time.h中,我们可以找到队clock的定义:#ifndef _CLOCK_T_DEFINEDtypedef long clock_t;#define _CLOCK_T_DEFINED#endif很明显,clock_t是一个长整形数。在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:#define CLOCKS_PER_SEC ((clock_t)1000)可以看到可以看到每过千分之一秒(1毫秒),调用clock()函数返回的值就加1。下面举个例子,你可以使用公式clock()/CLOCKS_PER_SEC来计算一个进程自身的运行时间:void elapsed_time(){printf(Elapsed time:%u secs.\n,clock()/CLOCKS_PER_SEC);}当然,你也可以用clock函数来计算你的机器运行一个循环或者处理其它事件到底花了多少时间:#include “stdio.h”#include “stdlib.h”#include “time.h”int main( void ){ long i =; clock_t start, finish; double duration; /* 测量一个事件持续的时间*/ printf( Time to do %ld empty loops is , i ); start = clock(); while( i-- ) ; finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC; printf( %f seconds\n, duration ); system(pause);}在笔者的机器上,运行结果如下:Time to doempty loops is 0.03000 seconds上面我们看到时钟计时单元的长度为1毫秒,那么计时的精度也为1毫秒,那么我们可不可以通过改变CLOCKS_PER_SEC的定义,通过把它定义的大一些,从而使计时精度更高呢?通过尝试,你会发现这样是不行的。在标准C/C++中,最小的计时单位是一毫秒。2、获得日历时间time_t time(time_t * timer);在time.h中,我们也可以看到time_t是一个长整型数:#ifndef _TIME_T_DEFINEDtypedef long time_t; /* 时间值 */#define _TIME_T_DEFINED /* 避免重复定义 time_t */#endif3、获得日期和时间3、1gmtime函数或localtime函数将time_t类型的时间日期转换为struct tm类型:使用time函数返回的是一个long值,该值对用户的意义不大,一般不能根据其值确定具体的年、月、日等数据。gmtime函数可以方便的对time_t类型数据进行转换,将其转换为tm结构的数据方便数据阅读。gmtime函数

文档评论(0)

1亿VIP精品文档

相关文档