c++ 11 std::chrono时间

1、duration_cast 时间转换

#include <iostream>
#include <string>
#include <chrono>

// 小时转化为分钟/秒等
int main()
{
	std::chrono::hours hour_time = std::chrono::hours(1);

	std::chrono::minutes minutes_time = std::chrono::duration_cast<std::chrono::minutes>(hour_time);

	std::chrono::seconds seconds_time = std::chrono::duration_cast<std::chrono::seconds>(hour_time);

	std::chrono::milliseconds milliseconds_time = std::chrono::duration_cast<std::chrono::milliseconds>(hour_time);

	std::chrono::microseconds microseconds_time = std::chrono::duration_cast<std::chrono::microseconds>(hour_time);

	std::cout << "1小时可转换为 \n"
		<< minutes_time.count() << "分钟 \n"
		<< seconds_time.count() << "秒 \n"
		<< milliseconds_time.count() << "毫秒 \n"
		<< microseconds_time.count() << "微秒" << std::endl;

	getchar();
	return 0;
}

2、now/time_point

now() 当前时间time_point
to_time_t() time_point转换成time_t秒
from_time_t() 从time_t转换成time_point

// 程序运行时间
#include <chrono>   
using namespace std;
using namespace chrono;

auto start = system_clock::now();
// do something...
auto end   = system_clock::now();

// 1
std::chrono::duration<double> runtime{end-start};
std::cout << runtime.count() << std::endl;	// count

// 2
auto duration = duration_cast<microseconds>(end - start);
cout <<  "花费了" 
     << double(duration.count()) * microseconds::period::num / microseconds::period::den 
     << "秒" << endl;
// system_clock example
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main ()
{
  using std::chrono::system_clock;

  std::chrono::duration<int,std::ratio<60*60*24> > one_day (1);

  system_clock::time_point today = system_clock::now();
  system_clock::time_point tomorrow = today + one_day;

  std::time_t tt;

  tt = system_clock::to_time_t ( today );
  std::cout << "today is: " << ctime(&tt);

  tt = system_clock::to_time_t ( tomorrow );
  std::cout << "tomorrow will be: " << ctime(&tt);

  return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值