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

时间:2019-09-29 16:18:10

标签: c++ performance stringstream fmt

从我在网上阅读的内容来看,fmt库应该比例如e.g.快得多。字符串流。

但是,我做了一些简单的基准测试(测量系统时间,请参见下面的代码),看来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

1 个答案:

答案 0 :(得分:1)

首先,我的计算机上没有得到相同的数字,对我来说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