How can i make cout faster?

Is there a way to make this run faster and do the same?

#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 ++ || OS: Windows

+6
c ++ performance cout console-application dev-c ++
source share
3 answers

As Mark B noted in the comments, first, line-to-line output should be faster:

 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; } 
+4
source share

Of course, use putchar from stdio.h .

+1
source share

The obvious solution is to declare the box array in different ways:

 char box[20][81]; 

Then you can cout string at a time. If you cannot do this for any reason, then there is no need to use std :: string here - the char array is faster:

 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? } 
+1
source share

All Articles