chrono是一个time library, 源于boost,现在已经是C++标准。

参考文章

duration & time_point

duration表示持续一段的时间 time_point 时间点.

std::this_thread::sleep_for()

sleep_for就是sleep, sleep until是到指定的time_point.

example

#include <chrono>
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <thread>

using namespace std;

typedef std::chrono::milliseconds Millseconds;
typedef std::chrono::duration<int, std::ratio<60*60>> Hours;
typedef std::chrono::duration<int, std::ratio<60>> Minitues;
typedef std::chrono::duration<int, std::ratio<60*60*24>> Days;


int main(int argc, char* argv[])
{
	using namespace std::chrono;
	Hours twanty_four_hour(24);
	Days one_day(1);

	cout << "A day has ";
	cout << Hours(one_day).count()  << " hours"<< endl;
	cout << Minitues(one_day).count()  << " minitues"<< endl;
	cout << Millseconds(one_day).count()  << " millseconds"<< endl;

	cout << "Up to now:\n";
	std::time_t tt;
	chrono::system_clock::time_point now = chrono::system_clock::now();
	tt = chrono::system_clock::to_time_t(now);
	cout << ctime(&tt) << endl;

	cout << "Add one day:\n";
	now +=  one_day;

	cout << "Add 24 hours:\n";
	now +=  twanty_four_hour;

	cout << "Two days later:\n";

	tt = chrono::system_clock::to_time_t(now);
	cout << ctime(&tt) << endl;


	cout << "Algo starts:\n";
	now = chrono::system_clock::now();
	//sleep(2);
	std::this_thread::sleep_for(Millseconds(2000));

	std::this_thread::sleep_until(system_clock::now() + Millseconds(2000));


	auto dur = chrono::duration_cast<chrono::duration<int>>(chrono::system_clock::now() - now);
	cout << "Cost ";
	cout << dur.count() << " seconds\n";
	cout << chrono::duration_cast<Millseconds>(dur).count() << " millseconds\n";
	return 0;
}

接受超时的函数

2018-01-29-11-24-42