《操作系统导论》第19章习题
目标:测算TLB的容量和访问TLB的开销
问题1:了解gettimeofday()
答:功能是获得当前精确时间。
头文件sys/time.h,函数原型 int gettimeofday(struct timeval*tv, struct timezone *tz)
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果,tz一般用NULL。
结构体timeval的定义:
struct timeval
{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
问题2:编程测试TLB大小
代码如下
#include
#include
#include
#include
#define NUMPAGES 2
#define PAGESIZE 4096
int main(int argc,char *argv[])
{
struct timeval tvbefore;
struct timeval tvafter;
int pagenum = atoi(argv[1]); //页的数目
int trynum = atoi(argv[2]); //尝试次数
int jump = PAGESIZE / sizeof(int);
int i = 0;
int count = 0;
int *nums = (int *)malloc(pagenum * jump * sizeof(int));
gettimeofday(&tvbefore,NULL);
//执行页修改过程
while(count < trynum)
{
for(i = 0;i < pagenum * jump;i += jump)
{
nums[i] += 1;
}
count++;
}
gettimeofday(&tvafter,NULL);
//计算花费时间
int sec = tvafter.tv_sec - tvbefore.tv_sec;
int usec = tvafter.tv_usec - tvbefore.tv_usec;
printf("second use = %d\n",sec);
printf("usecond use = %d\n",usec);
free(nums);
return 0;
}
使用上述代码进行实验,计算每个页平均访问时间。使用环境:Ubuntu12.04,Inter(R) i7-4710HQ 2.5GHz,循环1亿次。
页的数量(Pagenum)
访问每页的时间(Time used for per page)/ ns
1
0.45
2
0.42
3
0.42
4
1.66
5
0.44
6
0.42
7
0.41
8
0.43
9
0.45
10
0.45
11
0.63
12
0.68
....
....
可以看出访问时间在页数为11时有大的增加,基本可以确定一级TLB能存放10项左右。二级及以上由于时间原因没有进行测试。
问题5:如何防止编译器优化循环和变量
答:通常可以对变量使用volatile关键字修饰,或者修改编译过程中的参数。