Skip to content

Instantly share code, notes, and snippets.

@jerryc05
Created April 24, 2021 06:09
Show Gist options
  • Save jerryc05/3767139d6cd3e5497003b19492c4e6cd to your computer and use it in GitHub Desktop.
Save jerryc05/3767139d6cd3e5497003b19492c4e6cd to your computer and use it in GitHub Desktop.
Timing for accessing cache with TLB
#!usr/bin/env python3
from fractions import Fraction
if __name__ == '__main__':
cols = 60
titles = ('Memory Component', 'Hit Rate (in %)', 'Access Time (cycles)')
mcs = ('TLB', 'Cache', 'Main Mem', 'Disk')
hr_at: 'list[list[Fraction]]' = []
for mc in mcs:
hr_at.append([])
for title in titles[1:]:
hr_at[-1].append(Fraction(input(f'{title:21} of {mc}: ')))
print()
print()
print(f'{titles[0]} | {titles[1]} | {titles[2]}')
print(f'{"-"*len(titles[0])}-|-{"-"*len(titles[1])}-|-{"-"*len(titles[2])}')
for i in range(len(mcs)):
print(
f'{mcs[i]:{len(titles[0])}} | {float(hr_at[i][0]):{len(titles[1])-2}} % | {int(hr_at[i][1]):{len(titles[2])}}'
)
print()
print()
out = (
f'{hr_at[0][1]} + ', f'{float(1-hr_at[0][0]/100)} * ({hr_at[2][1]} + '
f'{float(1-hr_at[2][0]/100)} * {hr_at[3][1]}) + ', f'({float(hr_at[0][0]/100)} + {float(1-hr_at[0][0]/100)} * '
f'{float(hr_at[2][0]/100)}) * ({hr_at[1][1]} + ', f'{float(1-hr_at[1][0]/100)} * {hr_at[2][1]})'
)
maxout = len(max(out, key=len))
exp = ('TLB Access', 'TLB Miss + Page Walk', 'Cache Access', 'Cache Miss')
maxexp = len(max(exp, key=len))
print(' \x1b[33mAccess a Physically Addressed Cache\x1b[39m '.center(cols, '='))
for i in range(len(out)):
print(f' {out[i]:{maxout}}\t{exp[i]:>{maxexp}}')
print('-' * cols)
res = hr_at[0][1] + (1 - hr_at[0][0] / 100) * (hr_at[2][1] + (1 - hr_at[2][0] / 100) * hr_at[3][1]) + (
(hr_at[0][0] / 100) + (1 - hr_at[0][0] / 100) * (hr_at[2][0] / 100)
) * (hr_at[1][1] + (1 - hr_at[1][0] / 100) * hr_at[2][1])
print(f'\x1b[33m= {res} cycles')
print(f'= {float(res)} cycles\x1b[39m')
print()
print()
out = (
f'{hr_at[1][1]} + ', f'{float(1-hr_at[1][0]/100)} * ({hr_at[0][1]} + ',
f'{float(1-hr_at[0][0]/100)} * ({hr_at[2][1]} + ',
f'{float(1-hr_at[2][0]/100)} * {hr_at[3][1]} + {float(hr_at[2][0]/100)} * {hr_at[2][1]}) +',
f'{float(hr_at[0][0]/100)} * {hr_at[2][1]})'
)
maxout = len(max(out, key=len))
exp = ('Cache Access', 'TLB Access', 'TLB Miss + Page Walk', 'Page Hit + Fault', 'TLB Hit Mem Access')
maxexp = len(max(exp, key=len))
print(' \x1b[35mAccess a Virtually Addressed Cache\x1b[39m '.center(cols, '='))
for i in range(len(out)):
print(f' {out[i]:{maxout}}\t{exp[i]:>{maxexp}}')
print('-' * cols)
res = hr_at[1][1] + (1 - hr_at[1][0] / 100) * (
hr_at[0][1] + (1 - hr_at[0][0] / 100) *
(hr_at[2][1] + (1 - hr_at[2][0] / 100) * hr_at[3][1] +
(hr_at[2][0] / 100) * hr_at[2][1]) + (hr_at[0][0] / 100) * hr_at[2][1]
)
print(f'\x1b[35m= {res} cycles')
print(f'= {float(res)} cycles\x1b[39m')
print()
print()
'''
99.5
1
90
10
99.99
90
100
80000
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment