Hi guys
A while back I bought a fake 2TB microSD card. It was a deal that was too good to be true.
Thing is…the microSD card works. Well, I think it does.
So, I wrote a py to test the memory card, and I want your review of the code:
The basic principle of the program is to write 100MB files to the card and then to read back random files to test if that spot on the card works. I read back random files in case to avoid to “real card” symptoms:
a) The data being read back is cached and not stored on the card and
b) The older data is being overwritten by the new data.
I think this program is good because
a) It gives you real time feedback, 100MB at a time. You dont have to wait for the whole card to be read until a result is returned.
b) It returns the card read/write performance.
b) The test will run until there is no further space. It will test a 16GB card or a 16TB card. No need to specify the size of the card.
Tell me what you think of this program:
import os
import psutil
import time
import random
def generate_file_content(filename, size_in_mb):
content = "A" * (size_in_mb * 1024 * 1024 - len(filename)) + filename
return content
def write_file(folder, filename, content):
with open(os.path.join(folder, filename), 'w') as f:
f.write(content)
def read_and_verify_file(folder, filename):
with open(os.path.join(folder, filename), 'r') as f:
content = f.read()
return content.endswith(filename)
def get_memory_usage():
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
return memory_info.rss # in bytes
def main():
# folder = "C:\\Users\\joeo\\Downloads\\Verify\\"
folder = "D:\\"
size_in_mb = 100
file_index = 1
statusArray = []
while True:
last_time = time.time()
filename = f'testfile_{file_index}.txt'
content = generate_file_content(filename, size_in_mb)
write_file(folder, filename, content)
write_time = time.time() - last_time
last_time = time.time()
random_index = random.randint(1, file_index)
random_file = f'testfile_{random_index}.txt'
if read_and_verify_file(folder, filename):
print(f'\033[32m{filename} verified successfully.')
statusArray.append(1)
else:
print(f'Error verifying \033[31m{filename}.')
statusArray.append(0)
last_time = time.time()
if read_and_verify_file(folder, random_file):
print(f'\033[32m{random_file} verified successfully.')
statusArray[random_index-1] = 1
else:
statusArray[random_index-1] = 0
print(f'\033[31mError verifying \033[31m{random_file}.')
read_time = time.time() - last_time
higest_success = len(statusArray) - statusArray[::-1].index(1) - 1
print(f'\033[37mWrite Time: {write_time:.2f} ({size_in_mb/write_time:.2f}MB/s), Read Time {read_time:.2f} seconds ({100/read_time:.2f}MB/s), total files {file_index}, total verified {sum(statusArray)}, highest success {higest_success}, memory usage: {get_memory_usage() / (1024 * 1024):.2f} MB')
file_index += 1
if __name__ == "__main__":
main()