Page 1 of 1

### in C: Optimal way to measure elapsed time?

Posted: Tue Sep 17, 2013 11:19 pm
Hello everyone,

I have been solving questions in C, I had once attempted to solve them in Python like ~4 years ago
Don't want to offend anyone, but Python sucks and was absolutely boring...
anyway, this is just preference, similar to how I prefer manual over automatic, and is irrelevant to what I want to ask

in C, I have been using the following template appended to each one of my source codes to determine how much time has passed:

Code: Select all

``````#include <stdio.h>
#include <time.h>

...

printf ( "The number you are looking for is %d", count );
printf ( "\n... and took %d / %d seconds to compute that", clock(), CLOCKS_PER_SEC );

...``````
Now, initially my intention to print-out the elapsed time was to see if it took too long, like more than a minute or so, in which case I would proceed into making optimizations; and this thing works more than enough to do that...
But then I realized, with C, almost everything happens in a snap. This was one of the things that made me love C, along with it's syntax, how straightforward and plain it is.

And now, I think I want some more precision. I mean, I have solved 58, and almost 50% of the time it has displayed:

Code: Select all

``````The number you are looking for is blabla
... and took 0 / 1000 seconds to compute that``````
Haven't kept a true statistical track of it, but I think it should be around 90% of the time where I saw less than 50 clocks happening, and the rest of them being less than 100~150.
One exceptional time that I remember of, in which it took over a second, and that was so exceptional that it took something between 20~30 seconds, for which I felt obliged to optimize afterwards...

Anyway, the things I want to really know is:
- is this way of measurement reliable? should I be confident about reporting that it took ~0 milliseconds?
- is there a way to acquire more precision, like 10th or even 1000th of a millisecond?
- suggestions about how else to do it in C
- how you do it, if you are writing in C

### Re: in C: Optimal way to measure elapsed time?

Posted: Wed Sep 18, 2013 4:15 pm
I've stolen this from someone from a post thread. It's basically the same, but you can control when to start the timer.

Code: Select all

``````#include <time.h>
clock_t start; //declaration of time type variable
int main(){
start=clock();