Reference library

Concurrency & performance

asyncio, threading, multiprocessing, and profiling-friendly performance patterns.

6 matches
Concurrency & performance easy

How to Memoize Pure Functions with functools.lru_cache in Python

Use functools.lru_cache to memoize a pure Fibonacci function and avoid recomputing repeated values.

lru-cache memoization functools
Python
from functools import lru_cache


@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    """Return the nth Fibonacci number (0-indexed) using memoization."""
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


if __name__ == "__main__":
    for i in range(10):
        print(f"fibonacci({…
15 0 Open
Concurrency & performance medium

How to Use ProcessPoolExecutor for CPU Parallel Map in Python

Run a function over a sequence of inputs in parallel across multiple CPU cores with ProcessPoolExecutor.map.

concurrency processpoolexecutor parallelism
Python
from concurrent.futures import ProcessPoolExecutor
import math

def compute_square(num):
    return num * num

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

if __name__ == "__main__":
    numbers = rang…
11 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor in Python for Parallel Processing

Use ThreadPoolExecutor with executor.map to run a function over many inputs concurrently and collect ordered results.

concurrency threadpoolexecutor parallel
Python
def worker(item):
    return item * item

if __name__ == "__main__":
    from concurrent.futures import ThreadPoolExecutor
    numbers = list(range(1, 11))
    with ThreadPoolExecutor(max_workers=4) as executor:
        results = list(executor.map(worker, numbers))
    print("Input:  ", numbers)
    print("Results:", …
13 0 Open
Concurrency & performance medium

How to Use a Bounded Buffer with threading.Condition in Python

Implement a thread-safe bounded buffer using threading.Condition and show a producer–consumer example with exact output.

threading condition producer-consumer
Python
import threading
import time
import random

class BoundedBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.buffer = []
        self.condition = threading.Condition()

    def put(self, item):
        with self.condition:
            while len(self.buffer) >= self.capacity:
       …
14 0 Open
Concurrency & performance easy

How to Vectorize a Function with a Pure Python Fallback

Create a decorator that calls a scalar function directly for a single value and routes list inputs to a pure-Python fallback for vectorized processing without NumPy.

vectorization decorator fallback
Python
import math


def fallback_vectorize(func, fallback=None):
    """Vectorize a scalar function with a pure-Python fallback for lists."""
    if fallback is None:
        fallback = lambda x: [func(i) for i in x]

    def wrapped(*args):
        if len(args) == 1 and isinstance(args[0], (list, tuple)):
            retur…
14 0 Open
Concurrency & performance medium

Profile Memory Usage with tracemalloc Snapshot Diff in Python

Use tracemalloc to take two memory snapshots, compute a diff, and print the top changes (size and count) by line number.

tracemalloc memory-profile performance
Python
import tracemalloc

def profile_memory():
    tracemalloc.start()
    
    # Allocate some objects to track
    data = [i * 2 for i in range(10000)]
    text = "x" * 5000
    nested = {"key": [1, 2, 3], "value": (4, 5)}
    
    # Take first snapshot
    snapshot1 = tracemalloc.take_snapshot()
    
    # Free some mem…
11 0 Open

Browse by section

Each section groups closely related Python snippets.

Concurrency & performance — Python code examples

What you will find here

This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.