时间和日期
一、主要函数: time();ctime();strftime();localtime();gettimeofday();
二、
/*2010-09-18*/
/* 时间和日期 */
/*time() 返回值是以秒为单位的,ctime() 以固定的格式输出时间日期,strftime() 可以按照某种格式打印,也就是自定义打印格式。localtime() 返回符合认知的时间,gettimeofday() 可以精确到微秒。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef long long ll;
void caculateconsumeTime(struct timeval* begin,struct timeval* end)
{
ll b=begin->tv_sec * 1000000+ begin->tv_usec;
ll e=end->tv_sec * 1000000+ end->tv_usec;
printf("consume time=%lld(us)/n",(e-b));
}
int main(void)
{
time_t cur=time(NULL);/******** time() *************/
printf("time=%ld/n",cur);
printf("ctime=%s",ctime(&cur));/******* ctime() ****/
struct tm* res=localtime(&cur);/****** localtime() ******/
printf("year=%d/n", res->tm_year+1900);// 别忘了加上1900 !
printf("mon=%d/n", res->tm_mon+1);
printf("day=%d/n", res->tm_mday);
char buf[100];
strftime(buf,100,"%F %R",res);/****** strftime() *******/
printf("strftime=%s/n",buf);
struct timeval begin,end;
int i;
gettimeofday(&begin,NULL);/******* gettimeofday() *******/
for(i=0;i<10000000;i++){;
}
gettimeofday(&end,NULL);
caculateconsumeTime(&begin,&end);
exit(0);
}
三、例程
1 、
/*time.c*/
#include <stdio.h>
#include <time.h>
int main(void)
{
printf("time=%lld/n", (long long)time(NULL));
return 0;
}
/* 返回秒*/
2 、
/*ctime.c*/
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
time_t cur = time(NULL);
printf("%s/n", ctime(&cur));
return 0;
}
/* 以固定的格式输出日期时间, 返回值:char* 型*/
3 、
/*ctime.c*/
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
time_t cur = time(NULL);
printf("%s/n", ctime(&cur));
return 0;
}
/* 以固定的格式输出日期时间, 返回值:char* 型*/
4 、
/*gettimeofday.c*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
void caculateConsumeTime(struct timeval *begin,
struct timeval *end)
{
long long b = begin->tv_sec * 1000000 +
begin->tv_usec;
long long e = end->tv_sec * 1000000 +
end->tv_usec;
printf("Consume time = %lld/n", (e-b));
}
int main(void)
{
struct timeval begin, end;
int i;
gettimeofday(&begin, NULL);
for (i = 0; i < 10000000; i++) {
}
gettimeofday(&end, NULL);
caculateConsumeTime(&begin, &end);
return 0;
}
/* 微秒级,可以用于测试,以优化程序*/
5 、
/*strftime.c*/
#include <stdio.h>
#include <time.h>
int main(void)
{
char buf[100];
time_t cur = time(NULL);
struct tm *res = localtime(&cur);
strftime(buf, 100, "%F %R", res);
printf("%s/n", buf);
return 0;
}
/*strftime() 可以按照某种格式打印,也就是自定义打印格式。strftime() 的使用依赖于localtime() ?*/