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;
}