Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prints access times of HDD vs RAM
# Tests whether python optimizes file reads or not
# Spoiler: apparently it does but it doesn't make much of a difference for this experiment
import time
def count_time(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(f"Time: \t{format(end - start, '.9f')}s")
return wrapper
@count_time
def read_file_n_times(filename, n=1):
for _ in range(n):
with open(filename) as fp:
fp.read()
for _ in range(100):
read_file_n_times('hello.txt')
import time
def get_hdd_time():
start = time.time()
fp = open('hello.txt')
fp.read()
end = time.time()
return end - start
def get_ram_time():
arr = [i for i in range(1000)]
start = time.time()
a = arr[2]
end = time.time()
return end - start
if __name__ == '__main__':
samples = 100
total_hdd_time = 0
total_ram_time = 0
for i in range(samples):
total_hdd_time += get_hdd_time()
total_ram_time += get_ram_time()
print(f"Average HDD time: {format(total_hdd_time/samples, '.9f')}s")
print(f"Average RAM time: {format(total_ram_time/samples, '.9f')}s")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment