怎样才能让cout更快?

Mar*_*ark 6 c++ performance cout console-application dev-c++

有没有办法让这个运行更快,仍然做同样的事情?

#include <iostream>

int box[80][20];

void drawbox()
{
    for(int y = 0; y < 20; y++)
    {
        for(int x = 0; x < 80; x++)
        {
            std::cout << char(box[x][y]);
        }
    }
}

int main(int argc, char* argv[])
{
    drawbox();
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

IDE:DEV C++ || 操作系统:Windows

Mat*_*haq 4

正如 Marc B 在评论中所说,首先将输出放入字符串中应该会更快:

int box[80][20];

void drawbox()
{
    std::string str = "";
    str.reserve(80 * 20);

    for(int y = 0; y < 20; y++)
    {
        for(int x = 0; x < 80; x++)
        {
            str += char(box[x][y]);
        }
    }

    std::cout << str << std::flush;
}
Run Code Online (Sandbox Code Playgroud)

  • 哦,请预先分配该字符串。`std::string` 不一定具有像 `std::vector` 这样的优化分配模式。 (13认同)
  • @Matthieu M:我怀疑任何默认字符串实现都会保留 1600 字节。因此,在完成写入之前很可能会进行多次重新分配。预先预留所需空间是个好主意。 (2认同)