Which is correct time elapsed in running code

Hello,
i used two methods to compute time elapsed in one of my program
First is
from ctime library,
1
2
3
4
clock_t stop=clock();
...Loops...
clock_t start=clock();
cout<<"Time required : "<<(double)(stop-start)/CLOCKS_PER_SEC;


And Second from Bash command "time"
1
2
3
4
5
6
me@maths131:~$ gcc -Wall -fopenmp canon.cpp -lstdc++
me@maths131:~$ time ./a.out 1000 400
Time required : 10.29
real	0m5.187s
user	0m10.289s
sys	0m0.016s



Now as you can see one is exactly half of other. And i also computed time using stopwatch, it comes in favor of command "time".
I am confused which is right? And its important.

PS: if "time" is right, then suggest some commands to use that time in cpp code in runtime.
¿How is the `user' time longer than the `real' time?

real: time spend between invocation and termination
user: time that the process was executed.
__Keep in mind that there are other process that your processor needs to take care of. So your program is not always executing.
__By instance, if you try to read, or to output to the screen (that are slow devices) you process will be blocked till the operation fulfills.
sys: ¿administration? (process creation, commutation, etc)

¿which one do you want?
I want real time, i.e. the time i watched on stopwatch. Which is equal to time coming from "time" command.

user time > real time... Because code is a parallel algorithm and i was working on cpu with two (cores) threads. Thus time(user)*2 is displayed!
I didn't think of that.
Ok, I went trough the gnu-time source code. They use gettimeofday() in order to get microseconds precision.
1
2
3
4
5
6
7
#include <sys/time.h>


timeval start, end;
gettimeofday(&start, NULL);
//...
gettimeofday(&end, NULL);
timeval is defined in sys/types.h as
1
2
3
4
struct timeval{
     __time_t tv_sec;		/* Seconds.  */
     __suseconds_t tv_usec;	/* Microseconds.  */
};
Just be careful doing the difference.
Thanks, It helps trigerring time. :)
Topic archived. No new replies allowed.