Created
October 6, 2025 21:27
-
-
Save zanieb/811cd141691f64ac2a42037c2bda6e9a to your computer and use it in GitHub Desktop.
A simple example for demonstrating a free-threaded speedup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| from random import Random | |
| def worker(base, random): | |
| acc = base * 2 | |
| for i in range(1000): | |
| acc += i * (42 + random.randint(0, 100)) | |
| return acc | |
| def main(): | |
| with ThreadPoolExecutor() as executor: | |
| for i in range(1000): | |
| # Give each worker its own `Random` generator to avoid cross-thread contention | |
| executor.submit(worker, i, Random()) | |
| if __name__ == "__main__": | |
| t0 = time.time() | |
| main() | |
| t1 = time.time() | |
| print(f"Elapsed time: {t1 - t0:.2f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment