liv2hak
liv2hak

Reputation: 14970

time measurement total time vs cpu time

I wrote a sample program to understand the time measurement in C.Below is a small self contained example.I have a function do_primes() that calculates prime numbers.In the main() function between timing code I call do_primes() and also sleep for 20 milliseconds.I am measure time using struct timeval (which I understand returns clock time.) and also cpu_time using CLOCKS_PER_SEC.Now as I understand it,this denotes the time for which the CPU was working.

The output of the program is as follows.

Calculated 9592 primes.
elapsed time 2.866976 sec. 
cpu time used 2.840000 secs.

As you can see the differnece between the elapsed time and cpu time is

 0.026976 seconds OR 26.976 milliseconds.


1) Are my assumptions correct? 
2) 6.976 milliseconds is accounted for my the scheduler switch delay?


#include <stdio.h>
#include <sys/time.h>
#include <time.h>

#define MAX_PRIME 100000

void do_primes()
{
    unsigned long i, num, primes = 0;
    for (num = 1; num <= MAX_PRIME; ++num)
    {
        for (i = 2; (i <= num) && (num % i != 0); ++i);
        if (i == num)
            ++primes;
    }
    printf("Calculated %ld primes.\n", primes);
}
int main()
{
    struct timeval t1, t2;
    double elapsedTime;
    clock_t start, end;
    double cpu_time_used;
    int primes = 0;
    int i = 0;
    int num = 0;

    start = clock();

    /* start timer*/
    gettimeofday(&t1, NULL);

    /*do something */
    usleep(20000);

    do_primes();

    /* stop timer*/
    gettimeofday(&t2, NULL);
    end = clock();

    /*compute and print the elapsed time in millisec*/
    elapsedTime  =  (t2.tv_sec - t1.tv_sec) * 1000.0;      /* sec to ms*/
    elapsedTime +=  (t2.tv_usec - t1.tv_usec) / 1000.0;    /* us to ms */

    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("elapsed time %f sec. \ncpu time used %f secs.\n",(elapsedTime/1000),cpu_time_used);

    return 0;
}

Upvotes: 0

Views: 512

Answers (1)

caf
caf

Reputation: 239011

Your understanding is correct.

The additional 6.976ms might not mean anything at all, because it's possible that the clock() function only has a resolution of 10ms.

Upvotes: 3

Related Questions