code.py
1 # SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import os 7 8 9 # First, just write the file 'hello.txt' to the card 10 with open("/sd/hello.txt", "w") as f: 11 print("hello world", file=f) 12 13 print() 14 print("SD card I/O benchmarks") 15 16 # Test read and write speed in several scenarios: 17 # * 512 or 4096 bytes at a time 18 # * Writing 1 time or 16 times 19 # First write the content to the SD card, then read it back, reporting the 20 # time taken. 21 for sz in 512, 4096: 22 b = bytearray(sz) 23 for i in range(sz): 24 b[i] = 0xaa 25 for n in (1, 16): 26 with open("/sd/hello.bin", "wb") as f: 27 t0 = time.monotonic_ns() 28 for i in range(n): 29 f.write(b) 30 t1 = time.monotonic_ns() 31 32 dt = (t1-t0) / 1e9 33 print(f"write {len(b)} x {n} in {dt}s {n * len(b) / dt / 1000:.1f}Kb/s") 34 35 with open("/sd/hello.bin", "rb") as f: 36 t0 = time.monotonic_ns() 37 for i in range(n): 38 f.readinto(b) 39 t1 = time.monotonic_ns() 40 41 dt = (t1-t0) / 1e9 42 43 print(f"read {len(b)} x {n} in {dt}s {n * len(b) / dt / 1000:.1f}Kb/s") 44 print() 45 46 # Test "logging" speed and report the time to write each line. 47 # Note that in this test the file is not closed or flushed after each 48 # line, so in the event of power loss some lines would be lost. However, 49 # it allows much more frequent logging overall. 50 # 51 # If keeping data integrity is your highest concern, follow the logging 52 # example, not this logging benchmark! 53 print("logging test") 54 with open("/sd/log.txt", "wt") as logfile: 55 t0 = time.monotonic_ns() 56 for i in range(10000): 57 t1 = time.monotonic_ns() 58 dt = (t1-t0) / 1e9 59 print(f"Line {i}, {dt:2f}s elapsed", file=logfile) 60 t1 = time.monotonic_ns() 61 dt = (t1-t0) / 1e9 62 63 print(f"Logged 10000 lines in {dt} seconds, {dt*100:.0f}us/line") 64 sz = os.stat('/sd/log.txt')[6] 65 print(f"{sz} bytes written, {sz/dt/1000:.1f}Kb/s")