How to print nested loops quicker in c?

I am trying to create a maze like game in c with double arrays and macros. But it is taking the console way too long to printf the whole maze. Is there a faster method for this.

#define SIZER 25 //row
#define SIZEC 50 //column

#define WALL "\xDB"
#define MAN "O"
#define ENEMY "\x40"
#define EMPTY " "

void print_game()
{
    int i,j;
    for(i=0;i<SIZER;++i){
        for(j=0;j<SIZEC;++j){
            if(game[i][j]==w)
                printf(WALL);
            else if(game[i][j]==m)
                printf(MAN);
            else if(game[i][j]==x)
                printf(ENEMY);
            else if(game[i][j]==e)
                printf(EMPTY);
            if(j==SIZEC-1)
                printf("\n");
        }
    }
}

Upvotes: 1

Views: 70

Answers (2)

Bodo
Bodo

Reputation: 9855

This version creates a complete line before calling printf. This could be extended to combine the whole maze into a string as mentioned in Robert Stiffler's comment.

#define SIZER 25 //row
#define SIZEC 50 //column

#define WALL '\xDB'
#define MAN 'O'
#define ENEMY '\x40'
#define EMPTY ' '

void print_game()
{
    int i,j;
    char line[SIZEC + 1];
    for(i=0;i<SIZER;++i){
        for(j=0;j<SIZEC;++j){
            if(game[i][j]==w)
                line[j] = WALL;
            else if(game[i][j]==m)
                line[j] = MAN;
            else if(game[i][j]==x)
                line[j] = ENEMY;
            else if(game[i][j]==e)
                line[j] = EMPTY;
        }
        line[SIZEC] = '\0';
        printf("%s\n", line);
    }
}

Upvotes: 2

abelenky
abelenky

Reputation: 64682

printf is an incredibly slow function, because it needs to be able to parse complex strings with multiple % formatters and width-specifiers in them.

If you don't really need the rich functionality of printf switching to puts (put-string) or putchar (put-character) should be much faster.


I also like @RobertStifiller's comment suggesting that you append all the output into an in-memory array, then call an output function just once at the very end to print all data at once.

Upvotes: 2

Related Questions