我不了解以下行为
unsigned long begin_time = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
//some code here
std::cout << "time diff with arithmetic in cout: " << \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time << std::endl;
unsigned long time_diff = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time;
std::cout << "time_diff: " << time_diff << std::endl;
输出:
time diff with arithmetic in cout: <very large number (definitely not milliseconds)>
time_diff: <smaller number (definitely milliseconds)>
当我在cout中进行算术运算时,为什么
duration_cast
不起作用?我已经将unsigned int
和int
用于time_diff
变量,但是当我第一次在变量初始化或赋值内进行算术运算时,始终可以获得良好的输出。注意
我正在使用Visual Studio 2013(社区版)
最佳答案
您可能正在溢出unsigned long
(sizeof为4):
unsigned long begin_time = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
推荐的:
using namespace std::chrono;
auto begin_time = steady_clock::now();
//some code here
std::cout << "time diff with arithmetic in cout: " <<
duration_cast<milliseconds>(steady_clock::now() - begin_time).count() << std::endl;