任务调度与上下文切换时间测试

创建两个进程(实时进程)并在它们之间传送一个令牌,如此往返传送一定的次数。其中一个进程在读取令牌时就会引起阻塞。另一个进程发送令牌后等待其返回时也处于阻塞状态。发送令牌带来的开销与上下文切换带来的开销相比,可以忽略不计(经测试,一次管道传递约用时3ns左右)。 (利用管道传递令牌) 

方法一:使用gettimeofday()

//方法一:使用gettimeofday()获取当前时间

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <sched.h>
#include <sys/types.h>
#include <unistd.h>      //pipe()

int main()
{
    int x, i, fd[2], p[2];
	int tv[2];	//用于进程间数据通信
    char send    = 's';
    char receive;
    pipe(fd);
    pipe(p);
	pipe(tv);
    struct timeval tv_start,tv_end;
    struct sched_param param;
    param.sched_priority = 0;

    while ((x = fork()) == -1);
    if (x==0) {			//子进程
        sched_setscheduler(getpid(), SCHED_FIFO, &param);
        gettimeofday(&tv_start, NULL);
		write(tv[1], &tv_start, sizeof(tv_start));//保存数据,以便传递到父进程中进行计算
		//printf("Before Context Switch Time1.sec %u s\n", tv_start.tv_sec);
        //printf("Before Context Switch Time1.usec %u us\n", tv_start.tv_usec);		
        for (i = 0; i < 10000; i++) {
            read(fd[0], &receive, 1);
			//printf("Child read!\n");
            write(p[1], &send, 1);
			//printf("Child write!\n");
        }
        exit(0);
    }
    else {		//父进程
        sched_setscheduler(getpid(), SCHED_FIFO, &param);
        for (i = 0; i < 10000; i++) {
            write(fd[1], &send, 1);
			//printf("Parent write!\n");
            read(p[0], &receive, 1);
			//printf("Parent read!\n");
        }
        gettimeofday(&tv_end, NULL);
		//printf("After Context SWitch Time1.sec %u s\n", tv_end.tv_sec);
		//printf("After Context SWitch Time1.usec %u us\n", tv_end.tv_usec);
		
    }
	read(tv[0], &tv_start, sizeof(tv_start));	
	//printf("Before Context Switch Time2.sec %u s\n", tv_start.tv_sec);
	//printf("Before Context Switch Time2.usec %u us\n", tv_start.tv_usec);
	//printf("Before Context Switch Time %u us\n", tv_start.tv_usec);
    //printf("After Context SWitch Time2.sec %u s\n", tv_end.tv_sec);
	//printf("After Context SWitch Time2.usec %u us\n", tv_end.tv_usec);
	printf("Task Switch Time: %f us\n", (1000000*(tv_end.tv_sec-tv_start.tv_sec) + tv_end.tv_usec - tv_start.tv_usec)/20000.0);	
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值