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;
}