宏
CLOCKS_PER_SEC:每秒时钟周期数的表达式。
类型:
- clock_t:表示时钟滴答计数的类型。
- size_t:其中一个基本无符号整数类型的别名,是一种能够以字节为单位表示任何对象大小的类型
- time_t:表示时间的类型
- struct tm:包含日历日期和时间的结构体
会员 | 类型 | 含义 | 范围 |
---|---|---|---|
tm_sec | int | 一分钟后 | 0-60* |
tm_min | int | 一小时后的几分钟 | 0-59 |
tm_hour | int | 午夜时分 | 0-23 |
tm_mday | int | 这个月的某一天 | 1-31 |
tm_mon | int | 几个月以来 | 0-11 |
tm_year | int | 自1900年以来 | >=0 |
tm_wday | int | 星期天以来的几天 | 0-6 |
tm_yday | int | 自1月1日以来的几天 | 0-365 |
tm_isdst | int | 夏令时标志 |
在夏令时标记(tm_isdst 如果夏令时生效,则大于零如果信息不可用,则小于零。
*tm_sec一般来说0-59。额外的范围是适应某些系统的闰秒。
函数
- time():获取当地时间
- localtime():将time_t 转成struct tm
- mktime:将struct tm转成time_t
- difftime 求time_t 之间差多少秒
- char* ctime (const time_t * timer):返回时间字符串
- asctime():将struct tm返回时间字符串
等价于:
char* asctime(const struct tm *timeptr)
{
static const char wday_name[][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];
sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}
获取当地时间
源代码
#include<cstdio>
#include<ctime>
int main(){
time_t timer;
time(&timer);
struct tm* timers;
timers = localtime(&timer);
printf ("Current local time and date: %s", asctime(timers));
}
输出结果
Current local time and date: Tue Jul 16 21:37:48 2019
计时
源代码
#include<cstdio>
#include<ctime>
int main(){
clock_t start,end;
start = clock();
int ans=1;
for(int i=0;i<1e8;i++)ans++;
end=clock();
end -=start;
printf ("It took me %d clicks (%f seconds).\n",end,((float)end)/CLOCKS_PER_SEC);
//利用float强转,使输出精确
}
输出结果
It took me 260 clicks (0.260000 seconds).