Jump to content

Recommended Posts

Posted (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.

post-10231-0-06380600-1302101194_thumb.p

post-10231-0-07278700-1302101200_thumb.p

Edited by Bit Hunter
Posted

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';

Posted (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 by Bit Hunter

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...