函数,注意参数是指针类型。
注:相关教程知识阅读请移步到C++教程频道。
那么如何输出时间呢?可以简单的使用char *ctime(time_t *_v)函数和char *asctime(struct tm *_v)函数,要注意的是返回的字符串结尾包含换行符n。
#include <stdio.h>
#include <time.h>
int main()
{
struct tm st;
st.tm_year = 2016 - 1900;
st.tm_mon = 8;
st.tm_mday = 13;
st.tm_hour = 16;
st.tm_min = 30;
st.tm_sec = 0;
st.tm_isdst = 0;
time_t tt = mktime(&st);
printf("%s", asctime(&st));
printf("%s", ctime(&tt));
return 0;
}
上述程序输出:
Tue Sep 13 16:30:00 2016
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("%dn", CLOCKS_PER_SEC);这样确定,若输出1000,则证明是毫秒。
我们可以方便的用它来计算程序某一段语句所消耗的时间:
#include <stdio.h>
#include <time.h>
int main()
{
int i = 0;
printf("CLOCKS_PER_SEC: %ldn", CLOCKS_PER_SEC);
long c = clock();
while(i < 1<<30) i++;
printf("The while loop cost %ld.n", clock() - c);
c = clock();
for(i = 0; i < 1<<30; i++);
printf("The for loop cost %ld.n", clock() - c);
return 0;
}
上述程序输出:
CLOCKS_PER_SEC: 1000
The while loop cost 2234.
The for loop cost 2206.
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用C语言能带来一定的帮助,如果有疑问大家可以留言交流。
注:相关教程知识阅读请移步到C++教程频道。










