Created
November 15, 2011 17:20
-
-
Save rctay/1367671 to your computer and use it in GitHub Desktop.
[ruby] NUS 11/12 Sem 1 CS2100 Tutorial 11 Q2c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cache | |
def split(addr) | |
x = addr >> 3 | |
return [x & 3, x >> 2] | |
end | |
attr_reader :misses, :hits | |
def initialize | |
@misses = 0 | |
@hits = 0 | |
@cache = Array.new(4, nil) | |
end | |
def update(addr) | |
index, tag = split(addr) | |
old_tag = @cache[index] | |
r = !old_tag.nil? && old_tag == tag | |
if r | |
@hits += 1 | |
else | |
@cache[index] = tag | |
@misses +=1 | |
end | |
return r | |
end | |
end | |
def q2c | |
a = 0x1000 | |
b = 0x4010 | |
c = Cache.new | |
999.times do | |
a += 4 | |
b += 4 | |
c.update(a) | |
c.update(b) | |
c.update(a-4) | |
end | |
puts "hits: #{c.hits}" | |
puts "misses: #{c.misses}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment