【发布时间】:2010-11-18 01:24:22
【问题描述】:
Windows XP SP3。酷睿 2 双核 2.0 GHz。 我发现 boost::lexical_cast 的性能非常慢。想找出加快代码速度的方法。在 Visual c++ 2008 上使用 /O2 优化并与 java 1.6 和 python 2.6.2 进行比较,我看到以下结果。
整数转换:
c++:
std::string s ;
for(int i = 0; i < 10000000; ++i)
{
s = boost::lexical_cast<string>(i);
}
java:
String s = new String();
for(int i = 0; i < 10000000; ++i)
{
s = new Integer(i).toString();
}
python:
for i in xrange(1,10000000):
s = str(i)
我看到的时间是
c++:6700 毫秒
java:1178 毫秒
python:6702 毫秒
c++ 和 python 一样慢,比 java 慢 6 倍。
双重铸造:
c++:
std::string s ;
for(int i = 0; i < 10000000; ++i)
{
s = boost::lexical_cast<string>(d);
}
java:
String s = new String();
for(int i = 0; i < 10000000; ++i)
{
double d = i*1.0;
s = new Double(d).toString();
}
python:
for i in xrange(1,10000000):
d = i*1.0
s = str(d)
我看到的时间是
c++: 56129 毫秒
java:2852 毫秒
python:30780 毫秒
所以对于 doubles,c++ 实际上是 python 速度的一半,比 java 解决方案慢 20 倍!!。关于提高 boost::lexical_cast 性能的任何想法?这是否源于糟糕的 stringstream 实现,或者我们是否可以预期使用 boost 库会导致性能普遍下降 10 倍。
【问题讨论】:
-
-1 表示不成熟的社论和缺乏视角
-
我删除了“可怜”的评论,我同意这是不必要的。有趣的是,在修复 lexical_cast accu.org/index.php/journals/1375 方面似乎已经完成了一些工作。所以这意味着如果你在 2006 年人们停止维护它时使用这个库,你会看到性能额外下降 3-6 倍。毫无疑问,库的编写者是出色的 C++ 程序员,但不妨退后一步,问一下提供这种通用性的库是否会使效率变得不可能。对比一下 STL,它保留了效率和通用性。
-
@Barry Kelly:作为一名资深的 C++ 程序员,我会说“这太可悲了!”如果我也看到了这些结果! @Burkhard:我希望有一种方法可以拒绝像你这样毫无意义的头发分裂 cmets。
-
下面的文章有一组详细的结果对比boost lexical_cast和其他各种方法,结果不言而喻。 codeproject.com/KB/recipes/Tokenizer.aspx
-
当前版本的boost并不慢:boost.org/doc/libs/1_49_0/doc/html/boost_lexical_cast/…也许你可以重做你的测试并更新问题?
标签: c++ boost lexical-cast