考虑以下代码片段
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
using std::chrono::system_clock;
using std::chrono::milliseconds;
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
const auto duration = milliseconds(100);
const auto start = system_clock::now();
std::this_thread::sleep_for(duration);
const auto stop = system_clock::now();
const auto d_correct = duration_cast<nanoseconds>(duration).count();
const auto d_actual = duration_cast<nanoseconds>(stop - start).count();
std::cout << "Difference is " << d_actual << ", and it should be roughly " << d_correct << "\n";
}
我们期望的是差异大约在100000000左右,但实际上差了100039989。您可以查看此演示,在那里它完全正常运行。然而,在我的机器上安装了几个编译器,根据Stack Overflow上的这个答案,可能会导致配置错误。因此,我尝试了建议的修复方法:设置正确的LD_LIBRARY_PATH
。这是我尝试过的带有输出的组合之一(还有4.4和4.6等其他组合)。g++-4.7 time.cpp -pthread -std=c++11; LD_LIBRARY_PATH=/usr/lib/gcc/i686-linux-gnu/4.7/ ./a.out
差异为100126,应该大致为100000000
g++-4.7 time.cpp -pthread -std=c++11; LD_LIBRARY_PATH=/usr/lib/gcc/i686-linux-gnu/4.8/ ./a.out
差值为100132,应该大约是100000000
g++-4.8 time.cpp -pthread -std=c++11; LD_LIBRARY_PATH=/usr/lib/gcc/i686-linux-gnu/4.7/ ./a.out
差值为100085953,大致应该是100000000
g++-4.8 time.cpp -pthread -std=c++11; LD_LIBRARY_PATH=/usr/lib/gcc/i686-linux-gnu/4.8/ ./a.out
差异为100156418,应该大约为100000000。
无论如何,使用任何一个libstdc++
进行g++-4.8
编译都可以正常工作,而使用g++-4.7
编译则会导致破损的情况。
我在编译器/二进制调用方面有什么问题吗,还是g++-4.7
中存在Bug?(具体来说,这是g++-4.7.3
和g++-4.8.1
)。
对于(可能最丑陋的)解决方法,当然我可以测量一小段时间,将其与预期差异进行比较并得出因子。但是我非常希望以优雅的方式解决这个问题。
apt-get
安装了一些gcc版本。所以某个地方存在一个错误,我想知道是哪里。 - stefan