profiler

High-performance thread-safe telemetry and profiling engine.

The Profiler provides advanced metrics collection lock-free across all background ThreadPool worker processes and the primary Pygame execution loop. It tracks function execution times bound by strict memory caps to prevent tracking leaks and dumps fully aggregated JSON reports upon safe shutdown or fatal application crashes.

class profiler.ThreadSampleBuffer(max_samples)[source]

Bases: object

Isolated, memory-bounded buffer dedicated to a specific thread’s metrics.

Prevents data contention between threads by allocating isolated Deques for profiling categories. Ensures thread-safe metric aggregation.

Parameters:

max_samples (int) – The maximum number of profiling samples to retain per category.

record(category, elapsed_time)[source]

Record a single profiling sample for the specified category.

Parameters:
  • category (str) – Logical category name for the timing sample.

  • elapsed_time (float) – Elapsed time in nanoseconds to record.

Return type:

None

class profiler.Profiler(max_samples_per_category=10000)[source]

Bases: object

Production-grade game telemetry system.

Features: - Zero lock-contention during chunk generation/rendering. - No memory leaks (Bounded memory footprints). - Perfect multi-thread data aggregation (No data loss on thread exit). - Safe, synchronous, non-corrupting shutdown reports.

Parameters:

max_samples_per_category (int) – Limit on tracking samples to bound memory footprint.

start_frame()[source]

Called exclusively on the main game loop thread.

Return type:

None

end_frame()[source]

Called exclusively on the main game loop thread.

Return type:

None

record(category, elapsed_time)[source]

Records metrics completely lock-free relative to other concurrent threads.

Parameters:
Return type:

None

measure(category)[source]

Context manager for clean block profiling.

Parameters:

category (str)

Return type:

Generator[None, None, None]

profile_func(category=None)[source]

Return a decorator which profiles the wrapped function under category.

Parameters:

category (str | None) – Optional category name override; when None the function name will be used.

Returns:

A decorator that wraps callables and records timing samples.

Return type:

Callable[[Callable[[…], Any]], Callable[[…], Any]]

save_report(filename='profiling_results.json')[source]

Consolidates metrics across ALL active and dead background worker loops, and saves synchronously to prevent file corruption on application exit.

Parameters:

filename (str)

Return type:

None