《Cracking the Coding Interview》——第16章:线程与锁——题目2

2014-04-27 19:14

题目:如何测量上下文切换的时间?

解法:首先,上下文切换是什么,一搜就知道。对于这么一个极短的时间,要测量的话,可以通过放大N倍的方法。比如:有A和B两件事,并且经常一起发生,每件只需要花几纳秒。如果你把A事件连续做几百万次,而B时间只做了几次,这样就能排除B事件对于测量的影响。如果总时间S = mA + nB。当m >> n 时,A≈S / m。下面的测量方法类似于打乒乓球,在主线程和副线程间互相传递一个令牌,这个令牌可以是变量、管道之类的用于通信的工具。与此同时,利用操作系统提供的调度函数强制决定调度顺序,用于触发上下文切换。下面这份代码我是照着读完了才写的,初次碰见这个题目还真是无从下手,因为完全没有想到如何触发上下文切换。

代码:

 1 // 16.2 How to measure the time of a context switch?

 2 // reference code from http://blog.csdn.net/dashon2011/article/details/7412548

 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>

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     

60     return 0;

61 }

 

你可能感兴趣的:(interview)