Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串附加vs Ostringstream 我检查了下面两个C++程序的性能比较。一个程序通过字符串连接将字符串加载到一个字符串中。另一种方法是将字符串加载到ostringstream缓冲区_C++_String_Ostringstream - Fatal编程技术网

字符串附加vs Ostringstream 我检查了下面两个C++程序的性能比较。一个程序通过字符串连接将字符串加载到一个字符串中。另一种方法是将字符串加载到ostringstream缓冲区

字符串附加vs Ostringstream 我检查了下面两个C++程序的性能比较。一个程序通过字符串连接将字符串加载到一个字符串中。另一种方法是将字符串加载到ostringstream缓冲区,c++,string,ostringstream,C++,String,Ostringstream,按字符串: string mytext = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; string res; clock_t tStart = clock(); for(size_t i=0;i<10000000;++i) { res += mytext; } fprintf(std

按字符串:

    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);
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);
从以上两个程序的结果中,我发现在string append中加载数据比在ostringstream中加载数据要慢。但在打印结果时,ostringstream比字符串打印花费更多的时间

我的问题是,如何减少在字符串流中加载数据和使用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