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