String append vs Ostringstream

时间:2017-04-12 08:00:34

标签: c++ string ostringstream

我在c ++中检查了以下两个程序的性能比较。一个程序通过字符串连接将字符串加载到字符串中。另一个将字符串加载到ostringstream缓冲区中。

按字符串:

    string mytext = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
    string res;

    clock_t tStart = clock();
    for(size_t i=0;i<10000000;++i) { res += mytext; }

    fprintf(stderr,"Time taken  To Load: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    tStart = clock();
    cout<<res<<endl;

    fprintf(stderr,"Time taken To Print: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

结果:

Time taken  To Load: 3.31s
Time taken To Print: 1.37s

通过Ostringstream:

string mytext = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";

clock_t tStart = clock();

std::ostringstream buffer;

for(size_t i=0;i<10000000;++i) { buffer<<mytext; }

fprintf(stderr,"Time taken To Load: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
tStart = clock();
cout<<buffer.str()<<endl;

fprintf(stderr,"Time taken To Print: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

结果:

Time taken To Load: 2.55s
Time taken To Print: 2.97s

从上面两个程序的结果中,我发现字符串append中的加载数据比ostringstream慢。但是在打印结果时,ostringstream比字符串打印花费的时间更多。

我的问题是,如何使用ostringstream减少在字符串流中加载数据和打印数据的时间?有没有其他方法比这两种方法更快地完成这个过程?

0 个答案:

没有答案