c++ chrono duration_cast to milliseconds results in seconds

我们两清 提交于 2019-11-28 12:29:01

I think what's happening is that you are compiling with GCC 4.7 but the run-time linker is using the libstdc++.so from a different GCC version, and they are configured with different precision for std::chrono:system_clock. If you use LD_LIBRARY_PATH or suitable linker options to ensure you compile with GCC 4.7 and use its libstdc++.so then the results should be correct.

For example:

$ $HOME/gcc/4.7.1/bin/g++ -std=c++11 t.cc
$ ./a.out
1372693222
$ LD_LIBRARY_PATH=$HOME/gcc/4.7.1/lib64 ./a.out
1372693225128

The difference happens because the call to system_clock::now() is in the libstdc++.so library so the result depends on which library is used at run-time, but the duration_cast conversion from that value to milliseconds is done by inline templates which are instantiated at compile-time. If the compile-time conversion is not consistent with the run-time call then the results are inconsistent.

For GCC 4.8.1 the system_clock implementation was improved to always use the clock_gettime system call if it's available, which was not the case for 4.7, so it consistently uses the high-precision clock no matter how GCC was configured, which probably explains why you don't see the problem with 4.8.1.

You should always ensure the right version of libstdc++.so is used at run-time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!