Which is faster?

My friend's friend made a function for inputing unsigned integers. It's faster than scanf and much faster than cin. But I made a small change and I think it's a bit faster now. But I'm not sure. Here's the old function:
1
2
3
4
5
6
7
8
int scanInt ()
{
char c;
while (!isdigit (c = getchar ()));
int ret = c - '0';
while (isdigit (c = getchar ())) ret = (ret * 10) + (c - '0');
return ret;
}

e.g.
 
int i = scanInt ();


Here is the new function:
1
2
3
4
5
6
7
void scanInt (int *i)
{
char c;
while (!isdigit (c = getchar ()));
*i = c - '0';
while (isdigit (c = getchar ())) *i = (*i * 10) + (c - '0');
}


e.g.
1
2
int i;
scanInt (&i);


It doesn't really matter, but I'm curious about which one is faster.
Cheers!
It could be faster or it could be slower. My guess is that the first one is faster, if there is a difference at all. The difference is probably so small that it doesn't matter. The first function is less confusing so I would prefer that one.
Last edited on
What makes you think "returning" the value using a pointer could be faster than using return semantics (passing it back in a register)? In any case, this falls into the realm of micro-optimizations which you should stay away from unless the performance really matters and you know exactly what you're doing.

but I'm curious about which one is faster.

Speed measurements are done by measuring speed, not by theorizing.

More importantly, your version neither handles EOF nor negative numbers correctly.
Your new function is 1.04 times faster.

Cheers,
Jim
Did I just read something about optimizing I/O code? Ever heard the phrase "hurry up and wait"?
Why not find out?

Easy way: run the function xxxxxx times and find the number of micro/seconds from the start to the end and divide it by the number of running times.
@airman9519 Yes, helios is right - I should have made it clear that these were just timings of your code as written, sorry.

What he's trying to say is that the speed of execution will be limited by the IO access, so the timings are pretty meaningless. In fact, the 1st version is probably faster if you remove the I/O limitation.

If you want to give it a go, I timed the code by using ::QueryPerformanceCounter()

Cheers,
Jim
Topic archived. No new replies allowed.