怎样才能让cout更快?

时间:2011-01-25 02:13:37

标签: c++ performance console-application cout 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);
}

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

显而易见的解决方案是以不同方式声明box数组:

char box[20][81];

然后你可以一次cout行。如果由于某种原因你不能这样做,那么就不需要在这里使用std :: string - char数组更快:

char row[81] ; row[80] = 0 ;
for (int y = 0; y < 20; y++)
  {
  for (int x = 0 ; x < 80 ; x++)
    row[x] = char(box[x][y]) ;
  std::cout << row ;
  // Don't you want a newline here?
  }

答案 2 :(得分:1)

当然,请使用putchar中的stdio.h