您的位置:首页 > 其它

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

2014-04-27 19:26 405 查看
2014-04-27 19:14

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

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

代码:

// 16.2 How to measure the time of a context switch?
// reference code from http://blog.csdn.net/dashon2011/article/details/7412548 #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <sched.h>
#include <sys/types.h>
#include <unistd.h>

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐