tags:

views:

211

answers:

1

I'm using the times() function to measure the value but I'm not sure if my approach is correct. Please have a look and advice

struct tms tms_start, tms_end;
if (!(pid=fork()))
{
    //some necessary operations here
    times(&tms_start);
    execl(...);
}
else if (pid)
{
    //in parent
    int status;
    wait(&status);
    times(&tms_end);
    if (WIFEXITED(status))
    {
        if(WEXITSTATUS(status)==0)
        {
            clock_t real = tms_end.tms_cstime - tms_start.tms_stime
            float running_time = real/(double)sysconf(_SC_CLK_TK);
        }
    }
}
+5  A: 

You'll need to call times(&tms_start) before the call to fork(). In your code above, the tms_start variable is uninitialised in the parent since the parent never calls times(&tms_start).

struct tms tms_start, tms_end;
times(&tms_start);             // <-- here
if (!(pid=fork()))
{
    //some necessary operations here
    execl(...);
}
else if (pid)
{
    ...
Greg Hewgill
Ah I see. So this difference calculation is correct I guess? clock_t real = tms_end.tms_cstime - tms_start.tms_stime
If you want to measure the time taken by the kernel on behalf of the child process, then your expression is correct. However if (more likely) you want to measure the CPU time taken by the process itself, then use tms_cutime and tms_utime. Or, if you want to measure the actual wall-clock time taken, don't use times() at all and instead use time() or gettimeofday().
Greg Hewgill