Link to home
Start Free TrialLog in
Avatar of b_loco
b_loco

asked on

Real time in C, as in the UNIX time command

Hi !

I have to measure the execution time of several functions in a C program I wrote.

What I have now is this:

struct tms StartTime;
struct tms EndTime;
float StartTimeSeconds;
float EndTimeSeconds;

times(&StartTime);
...
times(&EndTime);
StartTimeSeconds = (float)StartTime.tms_utime/(float)CLOCKS_PER_SEC;
EndTimeSeconds = (float)EndTime.tms_utime/(float)CLOCKS_PER_SEC;
float t_total;
t_total = EndTimeSeconds-StartTimeSeconds;

I executed the program and the time of execution displayed was:

Execution time: 0.000066 seconds

I executed the UNIX time comand (as in "time program") and the result was:

Execution time: 0.000066 seconds
real    0m8.336s
user    0m0.660s
sys     0m0.240s

I could get to the user time by shifting the "." (sorry my english, hope you understand), but that's not what I want, I want the real time, even though I know that it takes in account the whole system and not just my program.

By changing the time field from tms_utime to tms_stime I can get the value of sys, but I can't get the real time
(by the way the "real" time was really about 8 secs).

How can this be achieved?

Thanks in advance

Avatar of Sjef Bosman
Sjef Bosman
Flag of France image

Use long time(&long) twice, once at the start, one at the end of the program. Granularity: 1 second :( There might be more sophisticated calls, depending on the actual Unix version you have.
Avatar of b_loco
b_loco

ASKER

I didn't quite understand your reply

you mean instead of :
times(&StarTime);

I should put:
long time(&long);

About the granularity, if i understood correctly, that wouldn't be a problem because the program is supposed to take more than 5 secs.
And I do not wish to make my program dependant to the OS so the more general the better. If required I would make it UNIX dependant, but I would like to avoid it.
ASKER CERTIFIED SOLUTION
Avatar of Sjef Bosman
Sjef Bosman
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of b_loco

ASKER

That incredibly simple solution solved it

Thank you :)