Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1531804
  • 博文数量: 113
  • 博客积分: 3526
  • 博客等级: 中校
  • 技术积分: 1815
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-08 09:46
个人简介

记录总结自己的工作

文章分类

全部博文(113)

文章存档

2015年(19)

2014年(10)

2013年(6)

2012年(16)

2011年(24)

2010年(21)

2009年(17)

分类: C/C++

2009-09-08 11:15:42

#include

void main( void )
{
         struct tm *newtime;
         char tmpbuf[128];
         time_t lt1;
         time( <1 );
         newtime=localtime(<1);
         strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", newtime);
         printf(tmpbuf);
}

运行结果:

Today is Saturday, day 30 of July in the year 2005.

4.5 计算持续时间的长度

         有时候在实际应用中要计算一个事件持续的时间长度,比如计算打字速度。在第1节计时部分中,我已经用clock函数举了一个例子。Clock()函数可以 精确到毫秒级。同时,我们也可以使用difftime()函数,但它只能精确到秒。该函数的定义如下:

double difftime(time_t time1, time_t time0);

         虽然该函数返回的以秒计算的时间间隔是double类型的,但这并不说明该时间具有同double一样的精确度,这是由它的参数觉得的(time_t是以秒为单位计算的)。比如下面一段程序:

#include "time.h"
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
     time_t start,end;
     start = time(NUL);
     system("pause");
     end = time(NUL);
     printf("The pause used %f seconds.\n",difftime(end,start));//<-
     system("pause");
     return 0;
}

运行结果为:
请按任意键继续. . .
The pause used 2.000000 seconds.
请按任意键继续. . .

         可以想像,暂停的时间并不那么巧是整整2秒钟。其实,你将上面程序的带有“//<-”注释的一行用下面的一行代码替换:

printf("The pause used %f seconds.\n",end-start);

其运行结果是一样的。

4.6 分解时间转化为日历时间

         这里说的分解时间就是以年、月、日、时、分、秒等分量保存的时间结构,在C/C++中是tm结构。我们可以使用mktime()函数将用tm结构表示的时间转化为日历时间。其函数原型如下:

time_t mktime(struct tm * timeptr);

其返回值就是转化后的日历时间。这样我们就可以先制定一个分解时间,然后对这个时间进行操作了,下面的例子可以计算出1997年7月1日是星期几:

#include "time.h"
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
     struct tm t;
     time_t t_of_day;
     t.tm_year=1997-1900;
     t.tm_mon=6;
     t.tm_mday=1;
     t.tm_hour=0;
     t.tm_min=0;
     t.tm_sec=1;
     t.tm_isdst=0;
     t_of_day=mktime(&t);
     printf(ctime(&t_of_day));
     return 0;
}

运行结果:

Tue Jul 01 00:00:01 1997

         现在注意了,有了mktime()函数,是不是我们可以操作现在之前的任何时间呢?你可以通过这种办法算出1945年8月15号是星期几吗?答案是否定 的。因为这个时间在1970年1月1日之前,所以在大多数编译器中,这样的程序虽然可以编译通过,但运行时会异常终止。

可以用clock函数来计算你的机器运行一个循环或者处理其它事件到底花了多少时间:

#include “stdio.h”
#include “stdlib.h”
#include “time.h”

int main( void )
{
   long    i = 10000000L;
   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 do 10000000 empty loops is 0.03000 seconds

上面我们看到时钟计时单元的长度为1毫秒,那么计时的精度也为1毫秒,那么我们可不可以通过改变CLOCKS_PER_SEC的定义,通过把它定义的大一些,从而使计时精度更高呢?通过尝试,你会发现这样是不行的。在标准C/C++中,最小的计时单位是一毫秒。

阅读(1534) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~