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;
}
}
I am making a Cache Simulator but I don't think my numHits() is working because the way I'm calling the value is wrong.
The problem is not the way you call the read()
method. Your numHits()
method always returns 0 because you return the value of a local variable, which is always initialized to 0.
numHits()
would only make sense if HitCounter
becomes an instance variable :
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;
}
I also changed return HitCounter++
to return ++HitCounter
, since post increment operator ( return HitCounter++
) will return the old value of HitCounter
instead of the incremented value.
EDIT : Another issue is that you pass to read
a variable that isn't declared anywhere. You should decide what you want to pass to that method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.