- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在查看我们的一些日志记录时,我注意到在分析器中我们花了很多时间在 operator<<
上。格式化整数等。看起来有一个共享锁,每当 ostream::operator<<
时都会使用。在格式化 int(并且可能是 double )时被调用。经过进一步调查,我将范围缩小到这个例子:
使用 ostringstream
的 Loop1进行格式化:
DWORD WINAPI doWork1(void* param)
{
int nTimes = *static_cast<int*>(param);
for (int i = 0; i < nTimes; ++i)
{
ostringstream out;
out << "[0";
for (int j = 1; j < 100; ++j)
out << ", " << j;
out << "]\n";
}
return 0;
}
Loop2 使用相同的 ostringstream
做除 int 格式之外的所有事情,这是用 itoa
完成的:
DWORD WINAPI doWork2(void* param)
{
int nTimes = *static_cast<int*>(param);
for (int i = 0; i < nTimes; ++i)
{
ostringstream out;
char buffer[13];
out << "[0";
for (int j = 1; j < 100; ++j)
{
_itoa_s(j, buffer, 10);
out << ", " << buffer;
}
out << "]\n";
}
return 0;
}
对于我的测试,我使用 1、2、3 和 4 个线程(我有一个 4 核机器)运行每个循环多次。试验次数是恒定的。这是输出:
doWork1: all ostringstream
n Total
1 557
2 8092
3 15916
4 15501
doWork2: use itoa
n Total
1 200
2 112
3 100
4 105
如您所见,使用 ostringstream 时的性能非常糟糕。添加更多线程时,它会变得更糟 30 倍,而 itoa 会快 2 倍左右。
一个想法是使用 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE)
根据 M$ in this article 的推荐.这似乎对我没有帮助。 Here's another user谁似乎有类似的问题。
我们需要能够在为我们的应用程序并行运行的多个线程中格式化整数。鉴于这个问题,我们要么需要弄清楚如何让它工作,要么找到另一种格式化解决方案。我可以编写一个简单的类,其中 operator<< 为整型和浮点类型重载,然后有一个模板化版本,它只在底层流上调用 operator<< 。有点难看,但我想我可以让它工作,虽然可能不适用于用户定义 operator<<(ostream&,T)
因为它不是 ostream
.
我还应该明确指出,这是使用 Microsoft Visual Studio 2005 构建的。而且我相信这种限制来自于他们对标准库的实现。
最佳答案
如果 Visual Studio 2005 的标准库实现有错误,为什么不尝试其他实现呢?喜欢:
甚至Dinkumware Visual Studio 2005 标准库基于它,也许自 2005 年以来就已经解决了这个问题。
编辑:您提到的其他用户使用的是 Visual Studio 2008 SP1,这意味着 Dinkumware 可能尚未修复此问题。
关于c++ - 跨线程扩展 MSVC 2005 的 operator<< 时的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1363817/
我是一名优秀的程序员,十分优秀!