0

I am trying to measure the average time of a context switch using threads and pipes, however when I use clock_gettime() I get an "undefined reference to clock_gettime()" even though I believe I have the appropriate header files. What the program is supposed to do is one thread writes data to a pipe and the other one reads the data, in this case the data is the time so as the measure the time of the context switch. The code I have is below:

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/time.h>
#include<time.h>

int fd[2];
int n = 0;
long now = 0;
int avg = 0;
struct timespec tv;

void * writeThread()
{
        for(n=1000;n>0;n--)
        {
                clock_gettime(CLOCK_MONOTONIC_RAW,&tv);
                now = tv.tv_nsec;
                write(fd[1],(void*)&now,sizeof(now));

                usleep(1000);
        }
        return 0;
}

void * readThread()
{
        for(n=1000;n>0;n--)
        {
                int time = read(fd[0],(void*)&now,sizeof(now));
                clock_gettime(CLOCK_MONOTONIC_RAW,&tv);
                now = tv.tv_nsec;
                int switchTime = now - time;
                avg = avg + switchTime;
        }
        avg = avg/1000;
        return 0;
}




int main(int argc, char ** argv) {

        pthread_t tid1,tid2;

        pthread_create(&tid1,NULL,writeThread,NULL);
        pthread_create(&tid2,NULL,readThread,NULL);
        /*pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        */
        printf("%d",avg);
        return 0;
}
KoolaidLips
  • 247
  • 1
  • 8
  • 20
  • 1
    Try adding `-lrt` to your link command. – Nikolai Fetissov Sep 13 '15 at 20:52
  • 2
    `clock_gettime` does not return the time. The function return value is a status. It returns the time in the pointer argument `struct timespec` which you are failing to supply. http://linux.die.net/man/3/clock_gettime – Weather Vane Sep 13 '15 at 20:55
  • @WeatherVane While I agree this makes the program logically wrong, shouldn't the error be a different error? Correct me if I'm wrong but it should still recognize the function. Also I was wondering if gettimeofday() would work in a similar fashion instead of clock_gettime. – KoolaidLips Sep 13 '15 at 21:08
  • It was a comment, not an answer. – Weather Vane Sep 13 '15 at 21:23
  • Once again, the man page reveals something useful. *"The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2). "* – Weather Vane Sep 13 '15 at 21:47

0 Answers0