测量上下文切换所需的平均时间

时间:2015-09-13 22:24:36

标签: c linux-kernel pthreads pipe

我正在尝试使用管道和线程来测量上下文切换所花费的时间,但是我注意到当我运行我的代码时,它只是打印先前初始化的值avg,即0.我的代码如下:

#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;
int avg = 0;
struct timespec tv;

void * writeThread()
{
        long now = 0;
        for(n=100000;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()
{
        long now = 0;
        for(n=100000;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;
        printf("%d",avg);
        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;
}

0 个答案:

没有答案