2024年5月31日发(作者:)
C语言中时间的基本用法
C语言中时间的基本用法
C语言是用电比较广泛的编程语言,但是对于C语言中时间的基
本用法你了解清楚了吗?下面店铺给大家介绍C语言中时间的基本用法,
欢迎阅读!
C语言中时间的基本用法
time_t和struct tm
在C语言中用time_t类型表示一个时间,通常它是一个和long
一样长的整数,也就是说,在32位环境下,它是4字节,在64位环
境下,它是8字节。它保存的就是一个整数值,表示了从1970-01-01
08:00:00到其所表示时间的秒数,它是一个非负整数,所以,time_t
无法表示早于1970-01-01 08:00:00的时间。
一个很常用的`函数就是time_t time(time_t *_v) ,它的参数是一
个time_t类型的指针,返回一个和传入参数相等的time_t类型值。如
果time()函数的参数是0,则返回当前的时间。
现在我们已经能用C语言表示一个时间了,但是这个时间只是从
某个时间开始的秒数,如何表示更详细的时间细节呢?这就要用到
struct tm类型了,它可以表示更具体的时间信息。
它一个结构体,我们就先看一下它的成员信息,一个struct tm类
型包括以下成员:
int tm_year表示时间的年份,它的值从1900年开始算起,也就
是说当其值为1的时候,表示的是1901年。因为time_t类型表示的
时间范围不早于1970年,所以这个值通常不小于70。
int tm_mon表示时间是几月,它的值是0到11,0表示的是一
月,而11表示的是12月。
int tm_mday表示时间是当前月的几号,其值的范围自然是根据
月份不同也不相同。
int tm_wday表示时间是星期几,它的值的范围是0到6,0是星
期天,1是星期一,6是星期六。
int tm_yday表示时间是当前年的第几天,要注意的是1月1号是
第0天。
int tm_hour表示时间是几时。
int tm_min表示时间是几分。
int tm_sec表示时间是几秒。
int tm_isdst表示是否是夏令时。
localtime()
如何把一个time_t类型构造成struct tm类型呢?用struct tm
*localtime(const time_t *_v)函数即可,注意参数和返回值都是指针
类型。
1
2
#include
3
#include
4
int main()
5
{
6
time_t tt = time(0); //获取当前时间
7
struct tm *pst = localtime(&tt); //把time_t类型转换为struct t
8
m类型
9
printf("The year is %d. ", pst->tm_year + 1900); //别忘了要加1900
1
return 0;
0
}
1
1
上述程序输出:
1 The year is 2016.
mktime()
那么如何把struct tm类型转换为time_t类型呢?就用time_t
mktime(struct tm *_v)函数,注意参数是指针类型。
那么如何输出时间呢?可以简单的使用char *ctime(time_t *_v)函
数和char *asctime(struct tm *_v)函数,要注意的是返回的字符串结
尾包含换行符 。
1
2
3
#include
#include
int main()
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
struct tm st;
_year = 2016 - 1900;
_mon = 8;
_mday = 13;
_hour = 16;
_min = 30;
_sec = 0;
_isdst = 0;
time_t tt = mktime(&st);
printf("%s", asctime(&st));
printf("%s", ctime(&tt));
return 0;
}
上述程序输出:
1 Tue Sep 13 16:30:00 2016
2 Tue Sep 13 16:30:00 2016
我们自己用struct tm构造了一个时间,并且在执行mktime()函
数后,tm_wday属性也会自动计算出来。
clock()
在time.h中,还有一些其他很常用的函数,比如clock_t clock()
函数,clock_t也是一个整数,是typedef long clock_t;得来的。这个
函数返回程序运行到这条语句所消耗的时间。单位一般是毫秒,可以
通过printf("%d ", CLOCKS_PER_SEC);这样确定,若输出1000,则证
明是毫秒。
我们可以方便的用它来计算程序某一段语句所消耗的时间:
1 #include
2 #include
3 int main()
4 {
5 int i = 0;
6 printf("CLOCKS_PER_SEC: %ld ", CLOCKS_PER_SEC);
7 long c = clock();
8 while(i < 1<<30) i++;
9 printf("The while loop cost %ld. ", clock() - c);
10 c = clock();
11 for(i = 0; i < 1<<30; i++);
12 printf("The for loop cost %ld. ", clock() - c);
13 return 0;
14 }
15
16
17
18
19
上述程序输出:
1 CLOCKS_PER_SEC: 1000
2 The while loop cost 2234.
3 The for loop cost 2206.
【 C语言中时间的基本用法】


发布评论