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()无法正常工作,因为我调用该值的方式是错误的。

最佳答案

问题不是您调用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一个未在任何地方声明的变量。您应该确定要传递给该方法的内容。

07-24 08:28