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