c语言随时间变化的函数 c语言时间随机函数( 二 )


利用上面这两个函数可以计算某阶段程序运行用掉的时间.
例如:
#include stdio.h
#include time.h
int main ()
{
time_t start,end;
char szInput [256];
double dif;
time (start);
printf ("Please, enter your name: ");
gets (szInput);
time (end);
dif = difftime (end,start);
printf ("Hi %s.\n", szInput);
printf ("You have taken %.2lf seconds to type your name.\n", dif );
return 0;
}
输出如下:
Please, enter your name: Juan Soulie
Hi Juan Soulie.
You have taken 3.00 seconds to type your name.
c语言时间处理函数C语言的标准库函数包括一系列日期和时间处理函数,它们都在头文件中说明 。
在头文件中定义了三种类型:time_t , struct tm和clock_t 。
下面列出了这些函数 。
time_t time(time_t *timer);
double difftime(time_t time1,time_t time2);
struct tm *gmtime(const time_t *timer);
struct tm *localtime(const time_t *timer);
char *asctime(const struct tm *timeptr);
char *ctime(const time_t *timer);
size_t strftime(char *s,size_t maxsize,const char *format,const struct tm *timeptr);
time_t mktime(struct tm *timeptr);
clock_t clock(void);
【具体应用举例】
asctime(将时间和日期以字符串格式表示)
相关函数
time,ctime,gmtime,localtime
表头文件
#i nclude
定义函数
char * asctime(const struct tm * timeptr);
函数说明
asctime()将参数timeptr所指的tm结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回 。
此函数已经由时区转换成当地时间 , 字符串格式为:"Wed Jun 30 21:49:08 1993\n"
返回值
若再调用相关的时间日期函数,此字符串可能会被破坏 。此函数与ctime不同处在于传入的参数是不同的结构 。
附加说明
返回一字符串表示目前当地的时间日期 。
范例
#i nclude
main()
{
time_t timep;
time (timep);
printf("%s",asctime(gmtime(timep)));
}
执行
Sat Oct 28 02:10:06 2000
ctime(将时间和日期以字符串格式表示)
相关函数
time,asctime,gmtime,localtime
表头文件
#i nclude
定义函数
char *ctime(const time_t *timep);
函数说明
ctime ()将参数timep所指的time_t结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回 。
此函数已经由时区转换成当地时间,字符串格式为"Wed Jun 30 21 :49 :08 1993\n" 。若再调用相关的时间日期函数,此字符串可能会被破坏 。
返回值
返回一字符串表示目前当地的时间日期 。
范例
#i nclude
main()
{
time_t timep;
time (timep);
printf("%s",ctime(timep));
}
执行
Sat Oct 28 10 : 12 : 05 2000
gettimeofday(取得目前的时间)
相关函数
time,ctime,ftime,settimeofday
表头文件
#i nclude
#i nclude
定义函数
int gettimeofday ( struct timeval * tv , struct timezone * tz )
函数说明
gettimeofday()会把目前的时间有tv所指的结构返回,当地时区的信息则放到tz所指的结构中 。
timeval结构定义为:
struct timeval{
long tv_sec; /*秒*/
long tv_usec; /*微秒*/
};
timezone 结构定义为:
struct timezone{
int tz_minuteswest; /*和Greenwich 时间差了多少分钟*/
int tz_dsttime; /*日光节约时间的状态*/
};
上述两个结构都定义在/usr/include/sys/time.h 。tz_dsttime 所代表的状态如下
DST_NONE /*不使用*/

推荐阅读