Last active
July 11, 2019 19:53
-
-
Save asm95/343a6411a0bc5b9031e38b7b22045310 to your computer and use it in GitHub Desktop.
Algoritmos de Alocação de Memória
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
# source: https://www.geeksforgeeks.org/program-best-fit-algorithm-memory-management/ | |
def print_allocation(n, allocation, process_size): | |
print("Process No.\tProcess Size\tBlock no.") | |
for i in range(n): | |
print("%d\t\t%d\t\t" % (i+1, process_size[i]), | |
allocation[i] + 1 if allocation[i] != -1 | |
else "Not Allocated", sep='' | |
) | |
def first_fit(block_size, process_size): | |
m = len(block_size) | |
n = len(process_size) | |
allocation = [-1] * n | |
for i in range(n): | |
for j in range(m): | |
if block_size[j] >= process_size[i]: | |
allocation[i] = j | |
block_size[j] -= process_size[i] | |
break | |
print_allocation(n, allocation, process_size) | |
def best_fit(block_size, process_size): | |
m = len(block_size) | |
n = len(process_size) | |
allocation = [-1] * n | |
for i in range(n): | |
best_idx = -1 | |
for j in range(m): | |
if block_size[j] >= process_size[i]: | |
if best_idx == -1: | |
best_idx = j | |
elif block_size[best_idx] > block_size[j]: | |
best_idx = j | |
if best_idx != -1: | |
allocation[i] = best_idx | |
block_size[best_idx] -= process_size[i] | |
print_allocation(n, allocation, process_size) | |
def worst_fit(block_size, process_size): | |
# stores block id of the block allocated to a process | |
# initially no block is assigned to any process | |
m = len(block_size) | |
n = len(process_size) | |
allocation = [-1] * n | |
# pick each process and find suitable blocks | |
# according to its size ad assign to it | |
for i in range(n): | |
wst_idx = -1 # (w)or(s)(t) (i)ndex | |
for j in range(m): | |
# if process fits in avaiable block | |
if block_size[j] >= process_size[i]: | |
if wst_idx == -1: | |
# pre-alocate this, because we don't know if we'll | |
# find another block in the list | |
wst_idx = j | |
elif block_size[wst_idx] < block_size[j]: | |
# if the last allocated block is smallar than the | |
# current candidate, then we'll opt to this larger | |
# one: this is the key part of wost-fit | |
wst_idx = j | |
if wst_idx != -1: | |
# if we could find a block for current process | |
# allocate block j to p[i] process | |
allocation[i] = wst_idx | |
# reduce available memory in this block | |
block_size[wst_idx] -= process_size[i] | |
print_allocation(n, allocation, process_size) | |
if __name__ == '__main__': | |
process_size = [13,14,6,19] | |
block_size = [6,14,19,13] | |
avail_functions = [first_fit, best_fit, worst_fit] | |
selected_fun = 1 | |
avail_functions[selected_fun](block_size, process_size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment