Bit Hunter Posted April 6, 2011 Share Posted April 6, 2011 (edited) Today i was not feeling like working with anything particular, so i decided to work on a little emulation of progress bar in ANSI C for a console app. Was wondering if there is anything that can be optimized in the code below? #include <stdio.h> #ifdef __MINGW32__ #include <windows.h> #else #define Sleep(t) usleep((t) * 1000) #endif int main(int argc, char **argv) { if (argc < 3) return 1; int len = atoi(argv[1]); int step = atoi(argv[2]); int i; char buf[len+1]; char c = '-'; float fstep = (float)len / (float)step; for (i = 0; i < len; i++) { buf[i] = '-'; buf[i+1] = '\0'; } printf("[%s] %c %02.0f\%\r", buf, c, 0.0); fflush(stdout); for (i = 1; i <= step; i++) { Sleep(3); int j, l; for (j = 0; j < len; j++) { if (j < i*(fstep)) { buf[j] = '#'; l = j; } else { buf[j] = '-'; } buf[j+1] = '\0'; } if (i != step) buf[l] = '>'; int k = i%4; if (k == 0) c = '-'; if (k == 1) c = '\\'; if (k == 2) c = '|'; if (k == 3) c = '/'; float per = i/(float)step*100; printf ("[%-*s] %c %02.0f%% \r", len, buf, c, per); fflush(stdout); } printf("\r\n"); return 0; } Should be able to compile with GCC as well as mingw32. Attached are the screenshots of the application running on lenny and xp. Edited April 6, 2011 by Bit Hunter Quote Link to comment Share on other sites More sharing options...
Jason Cooper Posted April 6, 2011 Share Posted April 6, 2011 Just looking at it and this loop jumps out as being inefficient. for (i = 0; i < len; i++) { buf[i] = '-'; buf[i+1] = '\0'; } Every time round the loop you put write to two locations in memory when you could do for (i = 0; i < len; i++) { buf[i] = '-'; } buf[i] = '\0'; Quote Link to comment Share on other sites More sharing options...
Bit Hunter Posted April 6, 2011 Author Share Posted April 6, 2011 (edited) Thanks, must have forgotten. I think switch is faster then if: if (k == 0) c = '-'; if (k == 1) c = '\\'; if (k == 2) c = '|'; if (k == 3) c = '/'; switch (k) { default: case 0: c = '-'; break; case 1: c = '/'; break; case 2: c = '|'; break; case 3: c = '\\'; break; } Edited April 6, 2011 by Bit Hunter Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.