The user wants a baseline performance test harness.
The harness needs to measure:
Latency
Throughput
Profiles (CPU/Memory)
I need to create a Python script that serves as this harness.
The harness should be modular so it can test arbitrary functions.
It needs to handle warmup, multiple runs, and statistical aggregation (mean, percentiles).
It should use standard libraries where possible (e.g., time, threading), but cProfile and memory_profiler (or tracemalloc) are good additions for profiling.
For concurrency (throughput), concurrent.futures or threading/multiprocessing is needed.
Plan:
Core Structure: Create a class PerfHarness.
Configuration: Allow setting duration, number of workers, warmup time.
Latency Test:
Run the target function repeatedly.
Record individual execution times.
Calculate Min, Max, Mean, Median, P95, P99.
Throughput Test:
Run the target function concurrently for a fixed duration.
Count total successful executions.
Report requests per second (RPS).
Profiling:
Use cProfile for CPU profiling.
Use tracemalloc or memory_profiler for memory snapshots.
Example Usage: Create a dummy function to demonstrate how the harness works.
Refining the implementation:
Latency: Just a loop. time.perf_counter() is best for precision.
Throughput: Needs a way to stop after a time limit. A common pattern is a loop running in threads until a shared stop event is set. Or simply running for N iterations and dividing by total time, but the user specifically asked for throughput often implying a sustained load. I'll implement a fixed-duration load test.
Profiling: cProfile is standard. memory_profiler is external, so maybe stick to tracemalloc (standard lib) or just provide the code snippet for cProfile to keep dependencies low, but the prompt asks for a "harness", so integrating it makes sense. I'll stick to cProfile for CPU and tracemalloc for memory to avoid pip install requirements for the baseline code.
Let's draft the code structure.
python
import time
import statistics
import cProfile
import pstats
import io
import tracemalloc
from concurrent.futures import ThreadPoolExecutor
The "Target" function should be replaceable. I will provide a dummy function that simulates work (e.g., sleeps or math operations) so the script runs out of the box.
Self-Correction on Throughput:
Throughput usually implies concurrency. If the function is blocking (IO bound), threads work. If CPU bound, processes work better. For a general baseline harness, ThreadPoolExecutor is safer default, but I should mention ProcessPool or AsyncIO. I will stick to Threads for simplicity but note the distinction.
Output formatting: Make it look like a report.
Let's write the code.
A robust baseline performance test harness should separate concerns: measuring raw speed (latency), capacity (throughput), and internal behavior (profiling).
Here is a complete, modular Python framework designed to test any arbitrary function. It uses only standard libraries (except numpy for statistical percentiles, though statistics can be used as a fallback).
1. The Performance Harness (perf_harness.py)
This script defines the PerformanceTester class. It handles warmup (to allow for JIT/OS caching), calculates percentile distributions, and runs concurrent load tests.
python
2. How to Use It (Example)
Below is an example usage. We define a dummy workload (simulating a database call or calculation) and pass it to the harness.
python
# main.py
import time
import random
# 1. Define the "System Under Test" (SUT)
def heavy_computation():
# Simulate IO or heavy processing
time.sleep(random.uniform(0.001, 0.010))
# Simulate some memory allocation
data = [i**2 for i in range(1000)]
return sum(data)
# 2. Run the Harness
if __name__ == "__main__":
# Initialize
tester = PerformanceHarness(heavy_computation)
# A. Baseline Latency (Single Thread)
tester.run_latency_test(iterations=5000)
print("\n")
# B. Throughput (Multi-threaded Load)
# Use threads=1 to compare overhead vs latency test
# Use threads=CPU_CORES*2 to find saturation point
tester.run_throughput_test(duration_sec=5, num_threads=4)
print("\n")
# C. Profiling (Finding bottlenecks)
tester.profile_cpu(iterations=1000)
tester.profile_memory(iterations=100)
3. Interpreting the Output
When you run this, you will see three distinct sections:
Latency Metrics:
P95/P99: These are critical. The "Average" lies; the P99 tells you how bad the experience is for 1% of your users (or slowest iterations).
Use case: Baseline regression testing. If P99 rises by 20% after a code change, you have a performance degradation.
Throughput Metrics:
Ops/Sec: The theoretical maximum capacity of the code under concurrency.
Saturation: If you increase threads from 4 to 8 and Ops/Sec stays flat (or drops), you have hit a locking or resource bottleneck (GIL, DB connection pool, etc.).
Profiles:
CPU (cumulative): Shows where the code spends the most time. If heavy_computation is at the top, that's your hotspot.
Memory: Shows which lines are allocating the most RAM. Helpful for finding leaks (if usage grows unbounded during the loop) or inefficient data structures.
4. Advanced Tips
Warmup: Python is an interpreted language. The first few runs are slower due to bytecode compilation and loading. The warmup parameter in run_latency_test ensures you measure steady-state performance.
Coordinated Omission: In the throughput test, we measure how many ops complete in a fixed time window. This avoids "coordinated omission" (where the measurement tool waits for the response before sending the next request, effectively hiding latency spikes).
GIL (Global Interpreter Lock): If your heavy_computation is CPU-bound (number crunching) rather than IO-bound (sleep/network), threading in Python will show poor scaling due to the GIL. For CPU-bound tasks, swap threading.Thread for multiprocessing.Process in the harness.
import time
import threading
import queue
import statistics
import cProfile
import pstats
import io
import tracemalloc
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import namedtuple
from functools import partial
# Named tuple for clean results reporting
TestResult = namedtuple('TestResult',
['total_time', 'ops_per_sec', 'latency_avg', 'latency_p95', 'latency_p99'])
class PerformanceHarness:
def __init__(self, target_func, *args, **kwargs):
"""
Initialize the harness with the function to test.
"""
self.target_func = partial(target_func, *args, **kwargs)
def _measure_latency(self):
"""Internal helper to measure single execution time."""
start = time.perf_counter()
self.target_func()
end = time.perf_counter()
return (end - start) * 1000 # Convert to milliseconds
def run_latency_test(self, iterations=1000, warmup=100):
"""
Measures raw execution speed with no concurrency pressure.
"""
print(f"--- Starting Latency Test (Iterations: {iterations}) ---")
# Warmup
for _ in range(warmup):
self.target_func()
# Measurement
latencies = []
start_time = time.time()
for _ in range(iterations):
latencies.append(self._measure_latency())
total_time = time.time() - start_time
# Calculate Stats
avg = statistics.mean(latencies)
rps = iterations / total_time
# Sorting for percentiles
sorted_lats = sorted(latencies)
p50 = sorted_lats[int(iterations * 0.50)]
p95 = sorted_lats[int(iterations * 0.95)]
p99 = sorted_lats[int(iterations * 0.99)]
max_lat = sorted_lats[-1]
print(f"Avg: {avg:.4f}ms | P50: {p50:.4f}ms | P95: {p95:.4f}ms | P99: {p99:.4f}ms | Max: {max_lat:.4f}ms")
return TestResult(total_time, rps, avg, p95, p99)
def run_throughput_test(self, duration_sec=5, num_threads=8):
"""
Measures maximum operations per second under concurrent load.
"""
print(f"--- Starting Throughput Test (Threads: {num_threads}, Duration: {duration_sec}s) ---")
completed_ops = 0
errors = 0
stop_flag = threading.Event()
def worker():
nonlocal completed_ops, errors
while not stop_flag.is_set():
try:
self.target_func()
completed_ops += 1
except Exception:
errors += 1
# Start Threads
threads = []
for _ in range(num_threads):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
# Run for duration
start_time = time.time()
time.sleep(duration_sec)
# Stop Threads
stop_flag.set()
for t in threads:
t.join()
total_time = time.time() - start_time
ops_per_sec = completed_ops / total_time
print(f"Total Ops: {completed_ops} | Throughput: {ops_per_sec:.2f} ops/sec | Errors: {errors}")
return TestResult(total_time, ops_per_sec, 0, 0, 0)
def profile_cpu(self, iterations=1000):
"""
Generates a CPU profile report using cProfile.
"""
print(f"--- Starting CPU Profile ---")
pr = cProfile.Profile()
pr.enable()
for _ in range(iterations):
self.target_func()
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats(20) # Print top 20 rows
print(s.getvalue())
def profile_memory(self, iterations=100):
"""
Generates a Memory profile snapshot using tracemalloc.
"""
print(f"--- Starting Memory Profile ---")
tracemalloc.start()
for _ in range(iterations):
self.target_func()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print("[ Top 5 Memory Allocations ]")
for stat in top_stats[:5]:
print(stat)
tracemalloc.stop()