Skip to content

Instantly share code, notes, and snippets.

@todbot
Created May 14, 2024 20:45
Show Gist options
  • Save todbot/6a3c8e5633a7267465775aa3afda99fd to your computer and use it in GitHub Desktop.
Save todbot/6a3c8e5633a7267465775aa3afda99fd to your computer and use it in GitHub Desktop.
Attempt to estimate cost of exception raise vs return in CircuitPython
# raise_vs_return_code.py -- Attempt to estimate cost of exception raise vs return in CircuitPython
# 14 May 2024 - @todbot
import time
import random
import gc
num_runs = 50000
# functions that do a small amount of something but really nothing
def do_something_return():
nstr = str(random.random())
return nstr
def do_something_raise():
nstr = str(random.random())
raise Exception(nstr)
print("num_runs:", num_runs)
gc.collect()
m1s = gc.mem_free()
st = time.monotonic()
for i in range(num_runs):
do_something_return()
t1 = time.monotonic() - st
m1 = m1s - gc.mem_free()
print("return t:", t1, "mem:", m1)
gc.collect()
m2s = gc.mem_free()
st = time.monotonic()
for i in range(num_runs):
try:
do_something_raise()
except Exception:
pass
t2 = time.monotonic() - st
m2 = m2s - gc.mem_free()
print(" raise t:", t2, "mem:", m2)
print("delta: %.3f secs, mem: %.3f bytes" % (t2/t1, m2/m1))
while True:
pass
@todbot
Copy link
Author

todbot commented May 14, 2024

On Adafruit CircuitPython 9.0.3 on 2024-04-04; LOLIN S3 MINI 4MB Flash 2MB PSRAM with ESP32S3, the results are pretty consistently like this:

num_runs: 50000
return t: 6.66699 mem: 13136
 raise t: 8.86987 mem: 19232
delta: 1.330 secs, mem: 1.464 bytes

That is, about 33% longer in time and about 46% more memory. The 33% longer in time is what I see in Python3.12 on MacOS too. (Python3 gc.mem_free() doesn't exist)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment