Skip to content

Instantly share code, notes, and snippets.

@Arfey
Last active April 21, 2026 10:56
Show Gist options
  • Select an option

  • Save Arfey/0c02cb63482167b44496315790f62517 to your computer and use it in GitHub Desktop.

Select an option

Save Arfey/0c02cb63482167b44496315790f62517 to your computer and use it in GitHub Desktop.
nogil example with if expression as key value
import sys, time, threading
test_dict = {i: None for i in range(1000)}
ITERS = 1_000_000
def reader(d, expression):
keys = list(d.keys())
n = len(keys)
for i in range(ITERS):
if expression:
_ = d[keys[1 if n == 0 else i % n]]
else:
key = 1 if n == 0 else i % n
_ = d[keys[key]]
#######################################################################################
##################################### Utils ###########################################
#######################################################################################
def run(d, num_threads, expression):
threads = [
threading.Thread(target=reader, args=(d, expression)) for _ in range(num_threads)
]
t0 = time.perf_counter()
for t in threads: t.start()
for t in threads: t.join()
return time.perf_counter() - t0
print(f"GIL enabled: {sys._is_gil_enabled()}")
print(f"{'Strategy type':<25}{'1t':>10}{'4t':>10}{'8t':>10}{'scaling 8t/1t':>18}")
print("-" * 73)
for name, d, expression in [
("expression key", test_dict, True),
("variable key", test_dict, False),
]:
t1 = run(d, 1, expression)
t4 = run(d, 4, expression)
t8 = run(d, 8, expression)
# Compute ops/sec scaling
ops_1 = ITERS / t1
ops_8 = 8 * ITERS / t8
print(f"{name:<25}{t1:>9.2f}s{t4:>9.2f}s{t8:>9.2f}s{ops_8/ops_1:>17.2f}x")
uvx python@3.14t main.py
GIL enabled: False
Strategy type 1t 4t 8t scaling 8t/1t
-------------------------------------------------------------------------
expression key 0.05s 0.33s 2.11s 0.18x
variable key 0.05s 0.05s 0.10s 3.58x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment