C++基础之std-先stringstream后cout

通常我们会看到在cout之前会采用stringstream,而不是直接输出。

    std::stringstream ss_1;
    ss_1 << "this is ";
    ss_1 << "test.\n";
    std::cout << ss_1.str() << std::endl;

如下实验后发现,其实直接cout的时间使用更少,但system的io也会比较大,但为什么要先使用stringstream呢?

原因是我们当时不需要直接输出到console上,而是想先存在,之后发送到文件,或发送到数据库等,其他输出,这样采用先stringstream后cout的方式,更能兼容算法的统一性。

#include <iostream>
#include <chrono>
#include <thread>
#include <sstream>
#include <iomanip>

int main(void)
{
    std::cout << "Fill:\n"
        << std::left << std::setfill(' ') << std::setw(12) << -1.23 << std::right << std::setfill(' ') << std::setw(12) << std::hex << std::showbase << 42 << '\n'
        << std::left << std::setfill(' ') << std::setw(12) << -1.3 << std::right << std::setfill(' ') << std::setw(12) << std::hex << std::showbase << 142 << '\n'
        << std::left << std::setfill(' ') << std::setw(12) << -1 << std::right << std::setfill(' ') << std::setw(12) << std::hex << std::showbase << 4142 << '\n';

    auto start = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> sum_diff_1 = start - start;
    std::chrono::duration<double> sum_diff_2 = start - start;
    std::chrono::duration<double> sum_diff_3 = start - start;

    unsigned int idx = 1000;
    while (idx--)
    {
        auto start_1 = std::chrono::high_resolution_clock::now();
        std::stringstream ss_1;
        for (unsigned int i = 0; i < 5; ++i) {
            ss_1 << "this is test.\n";
        }
        std::cout << ss_1.str() << std::endl;
        auto end_1 = std::chrono::high_resolution_clock::now();

        auto start_2 = std::chrono::high_resolution_clock::now();
        std::stringstream ss_2;
        for (unsigned int i = 0; i < 5; ++i) {
            ss_2 << "this is test." << std::endl;
        }
        std::cout << ss_2.str() << std::endl;
        auto end_2 = std::chrono::high_resolution_clock::now();

        auto start_3 = std::chrono::high_resolution_clock::now();
        for (unsigned int i = 0; i < 5; ++i) {
            std::cout << "this is test." << std::endl;
        }
        auto end_3 = std::chrono::high_resolution_clock::now();

        std::chrono::duration<double> diff_1 = end_1 - start_1;
        std::chrono::duration<double> diff_2 = end_2 - start_2;
        std::chrono::duration<double> diff_3 = end_3 - start_3;

        sum_diff_1 += diff_1;
        sum_diff_2 += diff_2;
        sum_diff_3 += diff_3;
    }

    std::cout << "ss \\n    " << sum_diff_1.count() << std::endl;
    std::cout << "ss endl  " << sum_diff_2.count() << std::endl;
    std::cout << "cout     " << sum_diff_3.count() << std::endl;

    getchar();
    return 0;
}
/*
ss \n    14.6097
ss endl  14.508
cout     13.9853
*/

阅读更多
版权声明: https://blog.csdn.net/qccz123456/article/details/80347035
文章标签: stringstream
个人分类: C/C++基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭