Chinaunix首页 | 论坛 | 博客
  • 博客访问: 926870
  • 博文数量: 335
  • 博客积分: 10287
  • 博客等级: 上将
  • 技术积分: 3300
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-08 15:29
文章分类

全部博文(335)

文章存档

2015年(4)

2014年(15)

2013年(17)

2012年(11)

2011年(12)

2010年(96)

2009年(27)

2008年(34)

2007年(43)

2006年(39)

2005年(37)

我的朋友

分类: C/C++

2009-09-27 11:15:15

#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日之前,所以在大多数编译器中,这样的程序虽然可以编译通过,但运行时会异常终止。

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