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

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

方法一:使用gettimeofday()

[cpp]  view plain copy
  1. //方法一:使用gettimeofday()获取当前时间  
  2.   
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <sys/time.h>  
  6. #include <time.h>  
  7. #include <sched.h>  
  8. #include <sys/types.h>  
  9. #include <unistd.h>      //pipe()  
  10.   
  11. int main()  
  12. {  
  13.     int x, i, fd[2], p[2];  
  14.     int tv[2];  //用于进程间数据通信  
  15.     char send    = 's';  
  16.     char receive;  
  17.     pipe(fd);  
  18.     pipe(p);  
  19.     pipe(tv);  
  20.     struct timeval tv_start,tv_end;  
  21.     struct sched_param param;  
  22.     param.sched_priority = 0;  
  23.   
  24.     while ((x = fork()) == -1);  
  25.     if (x==0) {         //子进程  
  26.         sched_setscheduler(getpid(), SCHED_FIFO, &param);  
  27.         gettimeofday(&tv_start, NULL);  
  28.         write(tv[1], &tv_start, sizeof(tv_start));//保存数据,以便传递到父进程中进行计算  
  29.         //printf("Before Context Switch Time1.sec %u s\n", tv_start.tv_sec);  
  30.         //printf("Before Context Switch Time1.usec %u us\n", tv_start.tv_usec);       
  31.         for (i = 0; i < 10000; i++) {  
  32.             read(fd[0], &receive, 1);  
  33.             //printf("Child read!\n");  
  34.             write(p[1], &send, 1);  
  35.             //printf("Child write!\n");  
  36.         }  
  37.         exit(0);  
  38.     }  
  39.     else {      //父进程  
  40.         sched_setscheduler(getpid(), SCHED_FIFO, &param);  
  41.         for (i = 0; i < 10000; i++) {  
  42.             write(fd[1], &send, 1);  
  43.             //printf("Parent write!\n");  
  44.             read(p[0], &receive, 1);  
  45.             //printf("Parent read!\n");  
  46.         }  
  47.         gettimeofday(&tv_end, NULL);  
  48.         //printf("After Context SWitch Time1.sec %u s\n", tv_end.tv_sec);  
  49.         //printf("After Context SWitch Time1.usec %u us\n", tv_end.tv_usec);  
  50.           
  51.     }  
  52.     read(tv[0], &tv_start, sizeof(tv_start));     
  53.     //printf("Before Context Switch Time2.sec %u s\n", tv_start.tv_sec);  
  54.     //printf("Before Context Switch Time2.usec %u us\n", tv_start.tv_usec);  
  55.     //printf("Before Context Switch Time %u us\n", tv_start.tv_usec);  
  56.     //printf("After Context SWitch Time2.sec %u s\n", tv_end.tv_sec);  
  57.     //printf("After Context SWitch Time2.usec %u us\n", tv_end.tv_usec);  
  58.     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);   
  59.     return 0;  
  60. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值