C++关于时间操作的学习(1)

计时函数clock()

头文件:#include<time.h>
函数定义:clock_t clock( );
clock_t 是用来保存时间的数据类型,是一个长整型。
CLOCKS_PER_SEC是一个常量,默认为每过1毫秒,调用clock() 函数返回的值就加1;因此,可以使用公式clock()/CLOCKS_PER_SEC来计算程序的运行时间。

int main()
{
	int a = 10;
	clock_t start = clock();
	while(a)
	{
		a--;
	}
	clock_t end = clock();
	double sum = (double)(end- start) / CLOCKS_PER_SEC;
	cout << "运行时间为:" << sum << endl;
}

日期时间结构体 tm

结构体 struct tm 的定义

struct tm {
          int tm_sec;   // 秒, 取值区间为[0,59] 
          int tm_min;   // 分, 取值区间为[0,59]
          int tm_hour;  // 时, 取值区间为[0,23] 
          int tm_mday;  // 一个月中的日期, 取值区间为[1,31] 
          int tm_mon;   // 月份(从一月开始, 0代表一月),取值区间[0,11]
          int tm_year;  // 年份, 其值等于实际年份减去1900 
          int tm_wday;  // 星期, 取值区间为[0,6], 其中0代表星期天, 1代表星期一,以此类推
          int tm_yday;  // 从每年的1月1日开始的天数, 取值区间为[0,365], 其中0代表1月1日, 1代表1月2日, 以此类推 
          int tm_isdst; // 夏令时标识符, 实行夏令时的时候, tm_isdst为正。不实行夏令时的进候, tm_isdst为0; 不了解情况时, tm_isdst()为负。
          };

time()函数

可以通过 time()函数来获得日历时间,函数原型为:
time_t time(time_t * timer);
参数 timer为自己设定的开始时间。
time_t 是一个长整型数,表示的时间(日历时间)是从一个时间点(timer)到此时的秒数;若将 timer设置成NULL,则只返回现在的日历时间。

int main()
{
	int a = 10;
	time_t start = time(NULL);
	while(a)
	{
		a--;
	}
	cout << "现在的日历时间为:" << start << endl;
}

localtime_s()函数的使用

函数原型:errno_t localtime_s(struct tm Tm, const time_t Time);**
参数 Tm 为时间结构体(struct tm)的指针,用来保存转化后的本地时间;参数 Time 指向之前获取的日历时间。
作用:将日历时间转化为本地时间,并保存在Tm指向的时间结构体变量
(tm tem)中。
如果成功,返回值则为零; 若失败,将返回错误代码。

#include<iostream>
#include<time.h>
using namespace std;
int main()
{
	int a = 10;
	time_t start = time(NULL);
	while (a)
	{
		a--;
	}
	tm tem;
	localtime_s(&tem,&start);
	cout << "年:" << tem.tm_year + 1900 << endl;
	cout << "月:" << tem.tm_mon + 1 << endl;
	cout << "日:" << tem.tm_mday << endl;
	cout << "时:" << tem.tm_hour << endl;
	cout << "分:" << tem.tm_min << endl;
	cout << "秒:" << tem.tm_sec << endl;
}

注意:

  1. localtime_s() 适用于windows下,而在Linux下则使用localtime_r(),其函数原型为struct tm* localtime_r(const time_t* timep, struct tm* result);
  2. 旧版使用的是localtime(),这个函数不安全,不适合当前(使用时会出错),这三种函数效果基本一样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值