Last active
October 17, 2020 13:13
-
-
Save gmelodie/bcdb30455812301d69d2e3d9e9971488 to your computer and use it in GitHub Desktop.
Prints access times of HDD vs RAM
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
# 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') |
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
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