Skip to content
Advertisement

Measuring Elapsed Time Using clock_gettime(CLOCK_MONOTONIC)

I have to elapse the measuring time during multiple threads. I must get an output like this:

Starting Time | Thread Number

00000000000   |   1

00000000100   |   2

00000000200   |   3

Firstly, I used gettimeofday but I saw that there are some negative numbers then I made little research and learn that gettimeofday is not reliable to measure elapsed time. Then I decide to use clock_gettime(CLOCK_MONOTONIC).

However, there is a problem. When I use second to measure time, I cannot measure time precisely. When I use nanosecond, length of end.tv_nsec variable cannot exceed 9 digits (since it is a long variable). That means, when it has to move to the 10th digit, it still remains at 9 digits and actually the number gets smaller, causing the elapsed time to be negative.

That is my code:

long elapsedTime;
struct timespec end;
struct timespec start2;
//gettimeofday(&start2, NULL);
clock_gettime(CLOCK_MONOTONIC,&start2);

while(c <= totalCount)
{   
    if(strcmp(algorithm,"FCFS") == 0)
    {
        printf("In SErunner count=%d n",count);
        if(count > 0)
        {
            printf("Count = %d n",count);
        
            it = deQueue();
            c++;
            tid = it->tid;

            clock_gettime(CLOCK_MONOTONIC,&end);
            
            usleep( 1000*(it->value));
            elapsedTime = ( end.tv_sec - start2.tv_sec);
            
            printf("Process of thread %d finished with value %dn",it->tid,it->value);
            fprintf(outputFile,"%ld %d %dn",elapsedTime,it->value,it->tid+1);
        }
}

Unfortunately, timespec does not have microsecond variable. If you can help me I will be very happy.

Advertisement

Answer

Write a helper function that calculates the difference between two timespecs:

int64_t difftimespec_ns(const struct timespec after, const struct timespec before)
{
    return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000000
         + ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec);
}

If you want it in microseconds, just divide it by 1000, or use:

int64_t difftimespec_us(const struct timespec after, const struct timespec before)
{
    return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000
         + ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec) / 1000;
}

Remember to include <inttypes.h>, so that you can use conversion "%" PRIi64 to print integers of int64_t type:

    printf("%09" PRIi64 " | 5n", difftimespec_ns(after, before));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement