Last active
January 31, 2025 14:18
-
-
Save adielbm/da3d44851c5d301b71bf8bd553e75eea to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| def cache_block_range(word_addresses, m, n, tag_width, address_width): | |
| block_size = 2 ** m | |
| index_mask = (1 << n) - 1 | |
| tag_mask = (1 << tag_width) - 1 | |
| # Cache structure: list of dictionaries to hold index, tag, and data range | |
| cache = [] | |
| mv_count, mt_count, hit_count = 0, 0, 0 | |
| print(f"{'Address':<10}{'Index':<10}{'Tag':<10}{'Data (word)':<25}{'Miss/Hit':<10}") | |
| print("=" * 65) | |
| for x in word_addresses: | |
| base_address = (x // block_size) * block_size | |
| ending_address = base_address + block_size - 1 | |
| index = (x // block_size) & index_mask | |
| tag = (x // block_size) >> n & tag_mask | |
| data_range = f"Mem[{base_address}, {ending_address}]" | |
| # Check cache for hit or miss | |
| found_index = False | |
| hit = False | |
| for entry in cache: | |
| if entry['index'] == index: | |
| found_index = True | |
| if entry['tag'] == tag: | |
| hit = True | |
| break | |
| if hit: | |
| miss_hit = 'Hit' | |
| hit_count += 1 | |
| elif found_index: | |
| miss_hit = 'Miss-Tag' | |
| mt_count += 1 | |
| else: | |
| miss_hit = 'Miss-Valid' | |
| mv_count += 1 | |
| # Add or update the cache entry | |
| if not found_index or not hit: | |
| cache.append({'index': index, 'tag': tag, 'data_range': data_range}) | |
| print(f"{x:<10}{index:<10}{tag:<10}{data_range:<25}{miss_hit:<10}") | |
| print(f"total miss tags: {mt_count}") | |
| print(f"total miss valids: {mv_count}") | |
| print(f"total hits: {hit_count}") | |
| # Example usage: | |
| word_addresses = [3,180,43,2,191,88,190,14,181,44,186,253] | |
| m = 2 # Block size exponent | |
| n = 3 # Index width | |
| tag_width = 21 # Tag width | |
| address_width = 28 # Address width | |
| cache_block_range(word_addresses, m, n, tag_width, address_width) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment