为什么std :: cout这么耗时?

Saa*_*aad 5 c++ c++11

我已经制作了一个程序来计算8个字符串"sharjeel"的排列.

#include <iostream>
#include <time.h>

char string[] = "sharjeel";
int len = 8;
int count = 0;

void swap(char& a, char& b){
    char t = a;
    a = b;
    b = t;
}
void permute(int pos) {
    if(pos==len-1){
        std::cout << ++count << "\t" << string << std::endl;
        return;
    }
    else {
        for (int i = pos; i < len;i++)
        {
            swap(string[i], string[pos]);
            permute(pos + 1);
            swap(string[i], string[pos]);
        }
    }
}

int main(){
    clock_t start = clock();
    permute(0);
    std::cout << "Permutations: " << count << std::endl;
    std::cout << "Time taken: " << (double)(clock() - start) / (double)CLOCKS_PER_SEC << std::endl;
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

如果我沿着它打印每个排列大约需要9.8秒来完成执行.

40314   lshaerej
40315   lshareej
40316   lshareje
40317   lshareej
40318   lshareje
40319   lsharjee
40320   lsharjee
Permutations: 40320
Time taken: 9.815
Run Code Online (Sandbox Code Playgroud)

现在,如果我更换线:

std::cout << ++count << "\t" << string << std::endl;
Run Code Online (Sandbox Code Playgroud)

有了这个:

++count;
Run Code Online (Sandbox Code Playgroud)

然后重新编译,输出是:

Permutations: 40320
Time taken: 0.001
Run Code Online (Sandbox Code Playgroud)

再跑一次:

Permutations: 40320
Time taken: 0.002
Run Code Online (Sandbox Code Playgroud)

使用g ++和-O3编译

为什么std :: cout相对耗时?有没有办法打印更快?

编辑:制作程序的C#版本

/*
 * Permutations
 * in c#
 * much faster than the c++ version 
 */

using System;
using System.Diagnostics;

namespace Permutation_C
{
    class MainClass
    {
        private static uint len;
        private static char[] input;
        private static int count = 0;

        public static void Main (string[] args)
        {
            Console.Write ("Enter a string to permute: ");
            input = Console.ReadLine ().ToCharArray();
            len = Convert.ToUInt32(input.Length);
            Stopwatch clock = Stopwatch.StartNew();
            permute (0u);
            Console.WriteLine("Time Taken: {0} seconds", clock.ElapsedMilliseconds/1000.0);
        }

        static void permute(uint pos)
        {

            if (pos == len - 1u) {
                Console.WriteLine ("{0}.\t{1}",++count, new string(input));
                return;
            } else {
                for (uint i = pos; i < len; i++) {
                    swap (Convert.ToInt32(i),Convert.ToInt32(pos));
                    permute (pos + 1);
                    swap (Convert.ToInt32(i),Convert.ToInt32(pos));
                }
            }

        }
        static void swap(int a, int b) {
            char t = input[a];
            input[a] = input[b];
            input[b] = t;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

40313.  lshaerje
40314.  lshaerej
40315.  lshareej
40316.  lshareje
40317.  lshareej
40318.  lshareje
40319.  lsharjee
40320.  lsharjee
Time Taken: 4.628 seconds
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

从这里开始,与std :: cout的结果相比,Console.WriteLine()似乎快了两倍.什么似乎减慢了std :: cout的速度?

Mik*_*kis 10

std::cout 最终导致调用操作系统.

如果您想要快速计算某些内容,则必须确保计算中不涉及任何外部实体,尤其是那些未考虑性能的实体,例如操作系统.

希望它运行得更快?您有两种选择:

  1. 替换<< std::endl;为<< '\n'.这将避免在每一行上将C++运行时的内部缓冲区刷新到操作系统.它应该会带来巨大的性能提升.

  2. 收集字符串列表中的所有输出,甚至只收集一个巨大的字符串,完成后,在一次调用中输出字符串列表或一个大字符串std::ios::sync_with_stdio(false);.

至于为什么它如此"耗时",(换句话说,慢),这是因为std::cout(并且最终是操作系统的标准输出流)的主要目的是多功能性,而不是性能.想一想:std::cout会调用操作系统; 操作系统将确定写入的文件实际上不是文件,而是控制台,因此它会将数据发送到控制台子系统; 控制台子系统将接收数据并将呈现它们; 在渲染数据时,将会滚动控制台窗口.这是一项非常多的工作.

至于C#版本,我不确定到底发生了什么,但可能发生的事情是完全不同的:在C#中你没有调用Console.Out.Flush(),所以你的输出被缓存,你没有遭受C++ std::cout << std::endl导致的开销导致每行都要刷新到操作系统.但是,当缓冲区变满时,C#必须将其刷新到操作系统,然后它会受到强大的托管到本机和本机到托管转换的影响,这种转换是其工作方式所固有的.

  • 同样作为第一行的`std :: ios :: sync_with_stdio(false);`也有所不同。 (2认同)