And*_*dré 0 c++ performance stringstream fmt
从我在线阅读的内容来看,fmt 库应该比例如 stringstreams 快得多。
然而,我做了一些简单的基准测试(测量系统时间,见下面的代码),似乎 fmt 总是比 stringstreams 慢。我有什么问题吗?
uint64_t start;
uint64_t stop;
long MAXCOUNT = 10000000;
std::srand(123);
int* numbers = new int[MAXCOUNT];
for ( int i = 0; i < MAXCOUNT; i++) {
numbers[i] = std::rand();
}
{
std::string result;
start = currentTimeInMillis();
for ( int i = 0; i < MAXCOUNT; i++) {
result += fmt::format("Number {} is great!", numbers[i]);
}
stop = currentTimeInMillis();
fmt::print("timing fmt : {} ms / string length: {}\n", stop-start, result.size());
}
{
std::string result;
std::stringstream ss;
start = currentTimeInMillis();
for ( int i = 0; i < MAXCOUNT; i++) {
ss << "Number " << numbers[i] << " is great!";
}
result = ss.str();
stop = currentTimeInMillis();
fmt::print("timing stds: {} ms / string length: {}\n", stop-start, result.size());
}
Run Code Online (Sandbox Code Playgroud)
这段代码的典型结果(优化级别 O3 - 更少更糟)是:
timing fmt : 1414 ms / string length: 264823200
timing stds: 1287 ms / string length: 264823200
Run Code Online (Sandbox Code Playgroud)
小智 6
首先,我的机器上没有得到相同的数字,对我fmt
来说更快:
timing fmt : 1713 ms / string length: 264825935
timing stds: 2483 ms / string length: 264825935
Run Code Online (Sandbox Code Playgroud)
二、为了得到一个公平的比较,替换
result += fmt::format("Number {} is great!", numbers[i]);
Run Code Online (Sandbox Code Playgroud)
和
fmt::format_to(std::back_inserter(result), "Number {} is great!", numbers[i]);
Run Code Online (Sandbox Code Playgroud)
这改善了(再次在我的机器上)的时间
timing fmt : 1153 ms / string length: 264825935
timing stds: 2482 ms / string length: 264825935
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1264 次 |
最近记录: |