c语言 时间详解

来源:互联网 发布:药品网络经营许可证 编辑:程序博客网 时间:2024/06/08 04:53
1、计时,clock返回从开始这个程序到调用时的时钟计时单元数,连续做10亿次自减运算大约4.3秒  如下


#include <stdio.h>
#include <time.h>  


void main()
{
long i = 1000000000L;


clock_t start ,end;
double duration;
printf("Time to do %ld empty loops is ", i);
start = clock();
while (i--);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC; //  3000/s
printf("%f seconds\n", duration);


return;
}






2、获得日历时间(时间戳)
#include <stdio.h>
#include <time.h>  


int main()
{
time_t lt;
lt = time(NULL);
printf("The Calendar Time now is %d\n", (int)lt);
return 0;
}


3、获得看起来正常的日期和时间


#include <stdio.h>
#include <time.h>  


int main()
{
struct tm *local;
time_t t;
t = time(NULL);   //先获得时间戳
local = localtime(&t);  //将日历时间转换为tm结构
printf("Local hour is: %d\n", local->tm_hour);
local = gmtime(&t);
printf("UTC hour is: %d\n", local->tm_hour);
return 0;
}






tm结构的定义
struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};




4、固定的时间格式


#include <stdio.h>
#include <time.h>  


int main()
{
struct tm ptr;
char str[26];   //注意大小,小于这个数会报错
time_t lt;
lt = time(NULL);
gmtime_s(&ptr,&lt);
asctime_s(str,sizeof(str),&ptr); //注意这个函数的参数
printf("%s",str);
ctime_s(str, sizeof(str), &lt);
printf("%s", str);
return 0;
}


5、自定义时间格式
#include <stdio.h>
#include <time.h>  


int main()
{
struct tm ptr;
time_t lt;
char str[80];
lt = time(NULL);
localtime_s(&ptr,&lt);
strftime(str, 100, "It is now %I %p\n", &ptr);
printf(str);
return 0;
}




6、计算持续时间的长度  (只能精确到秒)


#include <stdio.h>
#include <time.h>  
#include <stdlib.h>
int main()
{
time_t start, end;
start = time(NULL);
system("pause");
end = time(NULL);
printf("The pause used %f seconds.\n", difftime(end, start));//<-
system("pause");
return 0;
}




7、分解时间转化为日历时间


#include <stdio.h>
#include <time.h>  
#include <stdlib.h>
int main()
{
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;
}
0 0