为什么 {fmt} 比 std::stringstream 慢?

Why is {fmt} slower than std::stringstream?

根据我在网上阅读的内容,{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

首先,我的机器上没有得到相同的数字,对我来说 fmt 更快:

timing fmt : 1713 ms   /   string length: 264825935
timing stds: 2483 ms   /   string length: 264825935

其次,为了获得公平的比较,替换

result += fmt::format("Number {} is great!", numbers[i]);

fmt::format_to(std::back_inserter(result), "Number {} is great!", numbers[i]);

这将时间缩短到(再次在我的机器上)

timing fmt : 1153 ms   /   string length: 264825935
timing stds: 2482 ms   /   string length: 264825935