Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make cout faster?

Is there any way to make this run faster and still do the same thing?

#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

like image 763
Mark Avatar asked Jan 25 '11 02:01

Mark


People also ask

How to make your period come faster?

Take time for a good, warm bath when you want that your period comes faster. Add relaxing essential oils to your bath. Essential oils of lavender, citronella, and rose will help you to eliminate stress while taking a bath.

How to optimize your code to make it run faster?

There is always more room for improvement to make your code run faster. Sometime we can use certain programming tricks to make a code run faster at the expense of not following best practices such as coding standards, etc. Try to avoid implementing cheap tricks to make your code run faster. 1. Optimize your Code using Appropriate Algorithm

How to increase the speed of a C++ program?

If you use C or printf in C++ you should consider some other functions that could even more increase the speed of your program. For strings you could use puts, gets or their equivalents for file operations. Well they are not formatted and to write data in one way takes some time. 4. Using Operators

How can I make a cut heal faster?

Fortunately, there are a number of steps you can take to help cuts heal fast and allow you to go on with your life. Wash your hands. Before caring for your wound, you'll need to make sure your hands are clean so you don't transfer bacteria into the cut.


2 Answers

As Marc B said in the comments, putting the output into a string first 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;
}
like image 197
Mateen Ulhaq Avatar answered Oct 02 '22 07:10

Mateen Ulhaq


The obvious solution is to declare the box array differently:

char box[20][81];

Then you can cout a row at a time. If you can't do this for whatever reason, then there's no need to use std::string here -- a 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?
  }
like image 27
TonyK Avatar answered Oct 02 '22 09:10

TonyK