根据我在网上阅读的内容,{fmt} 库应该比字符串流快得多。
然而,我做了一些简单的基准测试(测量系统时间,见下面的代码),似乎 {fmt} 总是比字符串流慢。我有什么问题吗?
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());
}
此代码的典型结果(优化级别 O3 - 更少甚至更糟)是:
timing fmt : 1414 ms / string length: 264823200
timing stds: 1287 ms / string length: 264823200