class DirectMappedCache extends Cache {
private int logLineSize; //log_2 of the number of bytes per cache line
private int logNumLines; //log_2 of the number of cache lines
private TreeMap<String, CacheSlot> tmap;
public DirectMappedCache(int logLineSize, int logNumLines) {
//constructor that takes lengths of different fields
this.logLineSize = logLineSize;
this.logNumLines = logNumLines;
tmap = new TreeMap<String, CacheSlot>();
}
public boolean read(String addr) {
System.out.println("Read from address " + addr + ": ");
String tag = addr.substring(0,9);
String slotnumber = addr.substring(9,13);
String offset = addr.substring(13,16);
if(tmap.containsKey(slotnumber)){
CacheSlot temp = tmap.get(slotnumber);
if(temp.valid){
if(tag.equals(temp.tag)){
return true;
}
}
}
CacheSlot put = new CacheSlot();
put.valid = true;
put.tag = tag;
tmap.put(slotnumber, put);
return false;
}
public int numHits(){
int HitCounter = 0;
if(read(addr)){
return HitCounter++;
}
return 0;
}
}
我正在制作缓存模拟器,但我不认为我的numHits()正在工作,因为我调用该值的方式是错误的。
答案 0 :(得分:2)
问题不在于您调用read()
方法的方式。您的numHits()
方法始终返回0,因为您返回局部变量的值,该变量始终初始化为0.
numHits()
只有在HitCounter
成为实例变量时才有意义:
private int HitCounter = 0;
public int numHits(){
if(read(addr)){ // you should replace addr with some variable that you actually declare
return ++HitCounter;
}
return 0;
}
我还将return HitCounter++
更改为return ++HitCounter
,因为后增量运算符(return HitCounter++
)将返回旧值HitCounter
而不是递增值。
编辑:另一个问题是你传递给read
一个未在任何地方声明的变量。您应该决定要传递给该方法的内容。