GIL Knocker (gilknocker)

0.4.2 · active · verified Wed Apr 15

gilknocker is a Python library, with core components implemented in Rust, designed to measure Global Interpreter Lock (GIL) contention in Python applications. It provides a quick and dirty metric by spawning a background thread that periodically attempts to acquire the GIL and records the time taken. This is particularly useful for identifying GIL-bound sections of code without the overhead of a full profiler like `py-spy`. The current version is 0.4.2, and it supports Python 3.9 and newer.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `Knocker` class to measure GIL contention during the execution of a Python function. It initializes `Knocker` with recommended default intervals, starts the measurement, runs a simulated GIL-heavy function, stops the measurement, and then prints the collected metrics.

import time
from gilknocker import Knocker

def my_gil_heavy_function():
    # Simulate some GIL-bound work
    _ = [i*i for i in range(1_000_000)]

knocker = Knocker(
    polling_interval_micros=1000, # How frequently to re-acquire GIL
    sampling_interval_micros=10000, # How long to run polling routine
    sleeping_interval_micros=100000 # How long to sleep between sampling
)

print("Starting GIL contention measurement...")
knocker.start()

my_gil_heavy_function()

knocker.stop()
print("Stopping GIL contention measurement.")

metrics = knocker.get_metrics()
print(f"Average GIL acquisition time: {metrics.avg_acquisition_time_micros:.2f} microseconds")
print(f"Max GIL acquisition time: {metrics.max_acquisition_time_micros:.2f} microseconds")
print(f"Total samples: {metrics.total_samples}")

view raw JSON →