how to find speed of a statement?

n = 5;
a = n + 1; how much time will it takes?

a = n++ ; how much time will this statement takes?

which of the above statements is fast and why?
The question is pointless because the statements do entirely different things. For the former, the values of a and n afterwards are 6 and 5; and for the latter, 5 and 6.
You usually want to compare the execution times of things that do the same. You could compare how long it takes to boil an egg with how long it takes to walk from your home to the nearest pharmacy, but except in the oddest of situations, that comparison is utterly useless.

In any case, the speed of something too fast to measure, is normally measured by doing it many times, and measuring how long it took.
For example,
1
2
3
4
5
6
7
#include <ctime>

unsigned t0,t1;
t0=clock();
for (int a=0;a</*a large number*/;a++)
    //do something
t1=clock();
To measure something as insignificant as a basic integral arithmetic statement, 'a large number' will probably have to be very large.
Last edited on
Actually for statements that simple, I'd compile the code, look at the generated assembler, and
refer to the processor data sheet for the timings of the generated instructions. But there won't
necessarily be a simple answer, since memory accesses might be sufficed by the processor's
data cache in which case the instruction will be faster than if it had to go to memory.

But we're talking the difference between literally 2-3 clock cycles which, with CPUs at over a billion
cycles per second amounts to an infinitesimally small amount of time. ie, don't sweat the small
stuff.
Thanks helios and jsmith for your response.
But this is the question asked by an interviewer.
what should i had reply to that question?
"Don't be a tosser" is probably appropriate.
thank you
Topic archived. No new replies allowed.