The fastest way to output a 2D char array in C

I'm just working on a snake game project, but I just realized that the old one is printftoo slow to render a 15 * 45 two-dimensional array.

If you know any input / output to output it faster, please help me!

My goal is 0.10 - 0.15 s.

I also accept libraries, but I want to get full copyright: p: p.

for (y = 0; y < MAX_Y ; y++) 
 {
  printf ("\t");
  for (x = 0; x < MAX_X; x++)
   {
    printf ("%c", base[y][x]);  
   }
  printf ("\n");
 }
+4
source share
2 answers

Since you are not using real formatting and only print individual characters, you can use a simple function putchar():

for (y = 0; y < MAX_Y ; y++) 
 {
  putchar ('\t');
  for (x = 0; x < MAX_X; x++)
   {
    putchar(base[y][x]);  
   }
  putchar('\n');
 }

, 100 000, 3 /dev/null, :

  • 6.679u, 6.663u 6.766u printf,
  • 3.309u, 3.315u 3.312u putchar,
  • 0.263u, 0.261u 0.263u ( putchar_unlocked).

, :

  • 8.153u printf,
  • 3.862u putchar,
  • 0.634u putchar_unlocked.

:

  • 0: 09.46 printf,
  • 0: 07.75 putchar,
  • 0: 05.06 putchar_unlocked.

-Edit ---- single write ---------

puts, :

 char baseString[MAX_Y*(MAX_X+2)+1];
 int p = 0;
 for (int y = 0; y < MAX_Y ; y++) 
   {
     baseString[p++] = '\t';
     for (int x = 0; x < MAX_X; x++)
       {
         baseString[p++] = base[y][x];  
       }
     baseString[p++] = '\n';
   }
 baseString[p] = 0;
 puts(baseString); // or fwrite(baseString,p,1,stdout);

:

  • 0.448u, 1.155s 0: 04.99 (puts)
  • 0.418u, 1.077s, 0: 04.81 (fwrite)

, putchar_unlocked.

OSX 10.9, Intel Core i7 2.3Ghz.

+3

fwrite(base[y], MAX_X, 1, stdout)

0

All Articles