But note: if we do that, we are not capturing the variability of latency.
We can also have the child process send a summary (count and total time) and then the parent can compute.
However, if we want to profile CPU and memory of the child process, we can have the parent monitor the child process's resource usage.
Let's design:
Parent process:
- Spawns a child process that runs the target function in a loop for a given duration or number of iterations.
- The child process will record:
* number of operations
* total time spent (from the first operation start to the last operation end)
- The parent will monitor the child process's CPU and memory usage at intervals (using psutil) and then compute average.
But note: the child process might be doing nothing between operations? We assume the target function is called repeatedly.
We can have the child process do:
code
start = time.perf_counter()
for i in range(iterations):
op_start = time.perf_counter()
target_function()
op_end = time.perf_counter()
# accumulate total time and count
end = time.perf_counter()
total_ops = iterations
total_time = end - start # This includes the loop overhead and the function call overhead.
But note: the above measures the time from the start of the first operation to the end of the last, which includes the time between operations.
Alternatively, we can measure only the function call time by accumulating op_end - op_start for each operation? But that would require storing every latency or summing.
Let's do:
total_function_time = 0
for i in range(iterations):
op_start = time.perf_counter()
target_function()
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
Then average_latency = total_function_time / iterations
And the total wall time = end - start (which includes the loop overhead and any scheduling delays).
Throughput = iterations / (end - start)
However, note that if we are running for a fixed duration, we don't know the iterations in advance.
Let's design two modes:
code
Mode 1: Fixed number of iterations.
Mode 2: Fixed duration.
We'll let the user choose.
Steps for child process:
code
Now, for the parent process to monitor CPU and memory of the child process:
code
Now, let's code:
code
However, note: we are not capturing the min, max, and percentiles of latency. We are only capturing average.
If we want to capture percentiles, we would need to send all the latencies from the child to the parent, which could be a lot of data.
For a baseline, average might be enough.
But let's think: we can have the child compute the percentiles and send the summary? That would require storing all latencies in the child, which might be memory intensive if there are many operations.
Alternatively, we can use a streaming algorithm for percentiles? But that's complex.
Given the baseline, we'll stick with average.
If the user wants more detailed latency statistics, they can modify the harness.
Also, note that the child process might be affected by the system's scheduling and other processes. We are running in a separate process, but still on the same system.
We might want to set the child process to high priority? But that might not be fair.
We'll leave it as is.
Another note: the child process might be doing garbage collection, etc. We are measuring the function in a separate process, so the parent's GC won't affect it, but the child's GC will.
We are building a baseline, so we accept that.
Let's code accordingly.
However, note: the child process might have a different environment (like different memory limits) but we are running in the same Python interpreter? Actually, it's a separate process, so it has its own memory space.
We are using multiprocessing, which on Unix uses fork, so the child starts with a copy of the parent's memory? That might be heavy if the parent has a lot of data.
We can use 'spawn' to avoid that? But then we have to re-import the target function.
We'll leave it as fork (default on Unix) and hope the parent doesn't have too much data.
Alternatively, we can design the child function to take the target function as a picklable object? But the target function might not be picklable.
We are passing the target function from the parent to the child. On Unix with fork, the child gets a copy of the parent's memory, so the target function is available.
On Windows, we must use spawn, and then the target function must be picklable and defined at the top level? We'll assume the user defines the target function in a way that it can be pickled.
But note: if the target function is a lambda or a nested function, it might not be picklable.
We'll document that the target function must be picklable for Windows.
Alternatively, we can pass the target function as a string and import it in the child? That's too complex.
Let's assume the user will provide a picklable function.
Now, let's code the harness.
We'll also add an option to run the test in the same process (for debugging) but by default we use a separate process.
We'll also allow the user to pass arguments to the target function? We can extend the target to be a callable and then pass args and kwargs.
Let's change:
code
We'll have the harness take a callable and then in the child, we call:
self.target(*self.args, **self.kwargs)
But note: the target function might have side effects that are not Picklable? We are running in a separate process, so the parent's state is not affected.
We are good.
Let's code accordingly.
However, note: the target function might be a method of an object that is not picklable? Then we have a problem.
We can try to avoid that by having the user pass a function that is picklable.
Alternatively, we can run the test in the same process if the user sets multiprocess=False? But then we cannot measure the CPU and memory of the function in isolation.
We'll stick with multiprocessing.
Let's code.
We'll also add a timeout? The child might hang? We can set a timeout for the child process? But then we might not get the result.
We can have the parent wait for the child with a timeout and then kill it if it times out? But then we lose the result.
We'll leave that to the user to ensure the target function doesn't hang.
Code:
code
But note: the child process might have multiple threads? Then the CPU times might be the sum of all threads? We are using the process's CPU times, which includes all threads.
That's acceptable because we want the total CPU time used by the process.
However, if the target function is multi-threaded, then the CPU percent might be over 100%? Yes, because we are summing the CPU time of all threads.
But note: the busy_wait function is CPU intensive and will use 100% of one core? Actually, it's a busy loop, so it will use 100% of one core.
We expect:
code
throughput: about 10 operations per second (because each operation takes 0.1 seconds)
avg_latency: about 0.1 seconds
avg_cpu_percent: about 100% (if the process is single-threaded and we are measuring on one core) but note: the CPU percent is (total_cpu_time / total_wall_time) * 100.
If we run for 1 second and do 10 operations, each taking 0.1 seconds, then total_cpu_time should be about 1 second (if single-threaded) and total_wall_time is 1 second, so 100%.
However, note that the busy_wait function might not be exactly 0.1 seconds because of scheduling? We'll see.
Let's run it.
But note: the child process might be scheduled on a different core? That doesn't matter.
We'll run the example.
However, we must be cautious: the child process might be killed by the system if it uses too much CPU? We are just testing.
We'll run a simple test.
But note: the child process might be affected by the system load. We should run on an idle system.
We'll leave that to the user.
Now, let's consider the memory used: the busy_wait function doesn't allocate memory, so memory_used should be near 0.
We'll run and see.
However, note: the child process might have some memory overhead from the Python interpreter and the function call? But that should be constant.
We are measuring the difference from the start of the test to the end, so if the memory doesn't change, it should be 0.
But note: the child process might allocate memory for the loop and then free? But Python's memory allocator might not return memory to the OS, so we might see an increase? Possibly.
We'll see.
Let's code the example and run.
But note: we are using psutil which might not be installed. We'll make it an optional dependency? Or we can require it.
Since we are building a baseline, we can require psutil.
Alternatively, we can skip the CPU and memory profiling if psutil is not available? But then we cannot measure that.
We'll require psutil.
Now, let's code the example.
However, note: the child function might raise an exception? We should catch that and return an error.
We'll wrap the child function in a try-except and put the exception in the result queue? Or we can let the child fail and the parent will see that the queue is empty? We are currently raising an error if the queue is empty.
We can catch the exception and put a result with an error field? Let's do:
code
In child_func:
try:
... the test ...
except Exception as e:
result = {'error': str(e)}
result_queue.put(result)
return
Then in the parent, we check for 'error' in the result.
We'll do that.
Let's adjust.
Also, we might want to set the child process to a lower priority? We can set the nice value? But that might affect the results.
We'll leave it as is.
Let's code accordingly.
Final code with error handling.
We'll also add a timeout for the child? We can set a timeout in the join? But if the child hangs, we want to kill it.
We can do:
code
child_proc.start()
child_proc.join(timeout=30) # 30 seconds timeout?
if child_proc.is_alive():
child_proc.terminate()
child_proc.join()
raise RuntimeError("Child process timed out")
But then we might not get a result.
We'll let the user decide by not setting a timeout? Or we can set a very long timeout? We'll leave it without timeout for now.
We'll change the join to have a timeout? We'll not set a timeout by default, but the user can set a timeout in the harness? We don't have that parameter.
We'll leave it as is.
Now, let's code.
I'll create a comprehensive performance testing harness in Python that measures latency, throughput, and profiles resource usage. This will be modular and extensible.
# Custom function test
def my_function():
# Your code to test
time.sleep(0.01)
return sum(range(1000))
harness = PerformanceHarness(
test_name="my_custom_test",
warmup_iterations=5,
measurement_iterations=1000,
concurrency=4,
time_based=False
)
report = harness.run_full_test(
my_function,
profile_duration=2.0,
store_raw_latencies=True
)
# Access individual metrics
print(f"Throughput: {report.throughput.operations_per_second:.2f} ops/sec")
print(f"P99 Latency: {report.latency.p99:.4f} ms")
print(f"Peak Memory: {report.resources.peak_memory_mb:.2f} MB")
# Save to file
harness.save_report(report, "my_test_results.json")
Key Features
Latency Measurement:
Min, max, mean, median, p95, p99, standard deviation
Configurable warmup period
Raw sample storage option
Throughput Measurement:
Operations per second
Support for single-threaded and concurrent execution
Time-based or count-based testing modes
Resource Profiling:
Memory usage (peak and average)
CPU utilization (peak and average)
Context switches and thread counts
Memory allocation tracing with tracemalloc
Flexibility:
Any callable function can be tested
Configurable concurrency levels
Both time-based and count-based testing
Detailed JSON report output
Extensibility:
Modular design for adding new metrics
Customizable via dataclasses
Easy to extend for specific needs
Notes
Warmup: Always include warmup iterations to allow JIT compilation, caching, etc.
Concurrency: For I/O-bound functions, increasing concurrency should increase throughput
Resource Monitoring: Uses psutil for cross-platform resource monitoring
Memory Tracing: tracemalloc tracks Python memory allocations (not system memory)
Accuracy: For most accurate results, run on an idle system with consistent conditions
This harness provides a solid baseline that can be extended for specific testing needs like network latency, database queries, or API endpoint testing.
If fixed iterations:
run for exactly that many iterations, record total_function_time and total_wall_time.
If fixed duration:
run until the duration is reached, count the iterations, and record total_function_time and total_wall_time (from first op start to last op end?).
But note: in fixed duration, we might have an incomplete last operation? We should not count an incomplete operation.
We can do:
start_time = time.perf_counter()
end_time = start_time + duration
i = 0
total_function_time = 0
while time.perf_counter() < end_time:
op_start = time.perf_counter()
target_function()
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
i += 1
total_wall_time = op_end - start_time # This is the time from the start of the first operation to the end of the last.
But note: the condition checks at the beginning of the loop, so we might start an operation that would exceed the duration? We should break before starting an operation that would exceed the duration if we are being precise.
Alternatively, we can break after the operation if we exceed? But then we count the operation that went over.
Let's break before starting a new operation if the remaining time is less than a threshold? But we don't know how long the operation will take.
So, we can break at the beginning of the loop if the current time is already over the end_time? But then we might have a gap.
Alternatively, we can run the loop until the current time is less than end_time, and then after the loop, we have the last operation that might have completed after end_time? We don't want to count that.
So we can do:
while True:
now = time.perf_counter()
if now >= end_time:
break
op_start = now
target_function()
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
i += 1
Then total_wall_time = op_end - start_time # but note: the last op_end might be after end_time.
We want the total_wall_time to be the time from the first op_start to the last op_end that is within the duration? Actually, we want the time we spent running, which is from the first op_start to the last op_end, even if it exceeds the duration? But the duration is the time we intended to run.
Alternatively, we can set:
total_wall_time = end_time - start_time # This is the intended duration.
But then the throughput would be i / total_wall_time, which is the number of operations we completed in the intended duration.
However, note that we might have started an operation that completed after the intended duration? We broke before starting a new operation if we are already over, but the current operation might have started before the end and finished after.
We are counting that operation? Yes, because we break at the beginning of the loop. So the last operation we count is the one that started before the end and finished after.
So then the total_wall_time we are using (end_time - start_time) is less than the actual time from first op_start to last op_end? We are using the intended duration, not the actual.
We can use the actual time from the first op_start to the last op_end? But then the throughput would be i / (last_op_end - first_op_start) which is the actual time we spent.
Which one is correct?
Typically, in fixed duration tests, we run for a fixed wall time and then measure how many operations we completed in that time. So we should use the intended duration as the denominator for throughput.
But note: if we start an operation right at the end, and it takes 10 seconds, then we would have run for 10 seconds beyond the intended duration? We broke before starting that operation? Let's reexamine:
We break at the beginning of the loop if now >= end_time.
So if we start an operation at time t (which is less than end_time) and it finishes at t+10, then we have run for 10 seconds beyond the intended duration? But we did not start a new operation after that.
So the intended duration is from start_time to end_time, but we actually ran until the last operation finished.
We want to measure the throughput in the intended duration? But we completed one operation that started within the duration, so we count it.
So:
throughput = operations_completed / intended_duration
And the latency we measured is the time for each operation, including the one that went over? Yes.
But note: the last operation's latency is included in the average, but it might be longer because it was interrupted? No, it wasn't interrupted, it ran to completion.
So it's okay.
Alternatively, we can break after the operation if the op_end is after end_time? But then we would not count that operation? That seems unfair because it started within the duration.
So we count it.
Therefore, for fixed duration:
total_wall_time = end_time - start_time (intended duration)
throughput = i / total_wall_time
average_latency = total_function_time / i
But note: the total_function_time is the sum of the function call times, which includes the last operation that might have taken longer? Yes.
This is acceptable.
We can use psutil to get the child process's CPU and memory usage at intervals and then average.
Steps:
child_proc = multiprocessing.Process(target=child_func, args=(...))
child_proc.start()
Then in the parent, we can do:
p = psutil.Process(child_proc.pid)
cpu_percent = []
mem_info = []
while child_proc.is_alive():
cpu_percent.append(p.cpu_percent(interval=0.1))
mem_info.append(p.memory_info().rss) # or .vms, etc.
Then compute average CPU and memory.
But note: the child process might finish quickly and we might miss some samples? We can sample at a fixed interval until the child exits.
Alternatively, we can have the child process send a signal when it starts and ends, and the parent can record the resource usage at those times? But we want the average during the test.
Let's do:
parent:
start monitoring before starting the child? But then we include the child's process creation time? We want only during the test.
We can have the child send a message through a queue when it starts the test and when it ends.
But to keep it simple, let's assume we start monitoring right after starting the child and stop when the child exits. This might include some overhead of process creation and cleanup, but for baseline it might be acceptable.
Alternatively, we can have the child record its own resource usage at the start and end? But then we need to get that data back.
Since we are already sending the summary (iterations, total_function_time, total_wall_time) from child to parent, we can also have the child record its own resource usage at the start and end and then send the difference? But that would only give us the total user and system CPU time, not the averaged over time.
We want the average CPU and memory usage during the test.
Let's do:
In the child, at the beginning of the test (before the loop) and at the end (after the loop), we record:
start_resource = psutil.Process().cpu_times()
start_memory = psutil.Process().memory_info()
Then at the end:
end_resource = psutil.Process().cpu_times()
end_memory = psutil.Process().memory_info()
Then we can compute:
total_user_cpu = end_resource.user - start_resource.user
total_system_cpu = end_resource.system - start_resource.system
total_cpu_time = total_user_cpu + total_system_cpu
average_cpu_percent = (total_cpu_time / total_wall_time) * 100
memory_increase = end_memory.rss - start_memory.rss # but note: the memory might not be released until the end? We are interested in the memory used by the process during the test.
But note: the memory usage might fluctuate. We are only taking two points.
Alternatively, we can have the parent sample the child's memory and CPU at intervals and average.
Given the complexity, let's stick with the child reporting its own resource delta.
We'll have the child send:
(iterations, total_function_time, total_wall_time,
start_user_cpu, start_system_cpu, start_memory_rss,
end_user_cpu, end_system_cpu, end_memory_rss)
Then parent computes:
total_cpu_time = (end_user_cpu - start_user_cpu) + (end_system_cpu - start_system_cpu)
average_cpu_percent = (total_cpu_time / total_wall_time) * 100
memory_used = end_memory_rss - start_memory_rss # This is the net increase, but the peak might be higher.
But note: the child process might have allocated and freed memory during the test, so the net increase might be zero even if there was high memory usage.
So we need the peak memory? That's harder.
Given the complexity, let's stick with the net memory increase for now.
Alternatively, we can have the parent monitor the child's memory at intervals and take the peak? But that would require the parent to sample.
Let's change: the parent will monitor the child's memory and CPU at intervals and compute:
average_cpu = average of cpu_percent(interval=0.1) over the samples? But note: cpu_percent returns the utilization since last call. We want the average over the entire test.
We can do:
parent:
start_time = time.time()
cpu_percent_samples = []
mem_samples = []
while child_proc.is_alive():
cpu = p.cpu_percent(interval=0.1) # this blocks for 0.1 seconds and returns the average over that interval?
# Actually, cpu_percent(interval) returns the average over the interval, but if we call it repeatedly with interval=0.1, we get the average over each 0.1 second.
# We want the overall average? We can just take the average of the samples? But note: the samples are over 0.1 seconds each, and we are sampling at 0.1 seconds intervals? Then the average of the samples is the average CPU utilization over the test.
cpu_percent_samples.append(cpu)
mem_samples.append(p.memory_info().rss)
total_time = time.time() - start_time
avg_cpu = sum(cpu_percent_samples) / len(cpu_percent_samples) # but note: the samples are over 0.1 seconds each, and we are taking the average of these averages? Actually, if the sampling interval is fixed, then the average of the samples is the average CPU utilization over the entire time? Not exactly, because the intervals are consecutive and non-overlapping? We are sampling every 0.1 seconds and each sample is the average over the previous 0.1 seconds? Then the average of these samples is the average over the entire time? Yes, if we sample continuously.
But note: the first call to cpu_percent(interval) will block for 0.1 seconds and then return the average over that 0.1 seconds. Then we call again after 0.1 seconds? Actually, we are calling in a loop and each call blocks for 0.1 seconds? Then the total time of the loop will be approximately the number of samples * 0.1 seconds? But we are also doing other operations (like checking is_alive and getting memory). So the sampling interval might be a bit more than 0.1 seconds.
Alternatively, we can use:
cpu_percent = p.cpu_percent(interval=None) # non-blocking, returns the utilization since the last call? But we have to call it at least once to get a value.
Let's do:
p.cpu_percent(interval=0.1) # first call to set up?
Actually, the first call to cpu_percent(interval) will return the average over the interval, and subsequent calls without interval will return the utilization since the last call.
We want to sample every 0.1 seconds? Then we can do:
while child_proc.is_alive():
cpu = p.cpu_percent(interval=0.1) # this blocks for 0.1 seconds and returns the average over that 0.1 seconds.
mem = p.memory_info().rss
cpu_percent_samples.append(cpu)
mem_samples.append(mem)
Then the average CPU is the average of the samples? But note: each sample is the average over 0.1 seconds, and we are taking the average of these 0.1-second averages. That is the average CPU utilization over the entire test? Yes, because the test duration is the sum of the intervals (approximately).
But note: the last interval might be shorter if the child exits in the middle of the 0.1 second? Then we are averaging over a fixed interval? We are using the actual interval of 0.1 seconds for each sample? Actually, the cpu_percent(interval=0.1) will block for 0.1 seconds and then return the average over that 0.1 seconds. So each sample is exactly 0.1 seconds (except possibly the last one if the child exits during the block?).
We can adjust by using the actual time spent? But for simplicity, we assume each sample is 0.1 seconds.
Given the complexity and the fact that we are building a baseline, let's stick with the child reporting its own resource delta.
We'll have the child record:
start_time = time.perf_counter()
start_cpu = psutil.Process().cpu_times()
start_mem = psutil.Process().memory_info().rss
... run the test ...
end_time = time.perf_counter()
end_cpu = psutil.Process().cpu_times()
end_mem = psutil.Process().memory_info().rss
total_wall_time = end_time - start_time # note: this is the wall time of the entire child process test, including setup? We want only the test loop? We are including the time to get the start resources? That's negligible.
But note: we want the time of the test loop, which we already have as the total_wall_time from the loop? Actually, we have two wall times:
total_wall_time_loop = end_time_loop - start_time_loop (where start_time_loop is set just before the loop and end_time_loop just after)
We'll use the loop's total_wall_time for throughput and latency.
And for the CPU and memory, we use the delta from the start of the test (which includes the loop setup) to the end? That's acceptable because the setup is negligible.
So we'll have the child send:
{
'iterations': iterations,
'total_function_time': total_function_time,
'total_wall_time': total_wall_time_loop,
'start_user_cpu': start_cpu.user,
'start_system_cpu': start_cpu.system,
'start_mem_rss': start_mem,
'end_user_cpu': end_cpu.user,
'end_system_cpu': end_cpu.system,
'end_mem_rss': end_mem,
}
Then parent computes:
total_cpu_time = (end_user_cpu - start_user_cpu) + (end_system_cpu - start_system_cpu)
average_cpu_percent = (total_cpu_time / total_wall_time_loop) * 100 # note: using the loop's wall time? Or the entire test wall time? We used the loop's wall time for the test, so we should use that for CPU as well? But the CPU time we measured includes the entire child process from start to end? We set start_cpu at the beginning of the test function (before the loop) and end_cpu after the loop, so that's the same as the loop's wall time? Not exactly, because there might be a small delay between setting start_cpu and starting the loop? But negligible.
memory_used = end_mem_rss - start_mem_rss
But note: the memory_used might be negative if the process freed memory? Then we might want the peak memory? We can't get that from two points.
Given the baseline, we might accept the net memory change.
We'll have:
class PerfTestHarness:
def __init__(self, target, duration=None, iterations=None, warmup=0):
self.target = target
self.duration = duration # in seconds
self.iterations = iterations
self.warmup = warmup # number of warmup iterations to run before measuring
def run(self):
# We'll run the test in a separate process.
# We'll use a multiprocessing.Process and a queue to get the results.
result_queue = multiprocessing.Queue()
def child_func():
# We do the warmup if needed?
# But note: the warmup should be part of the test? Or before the measurement?
# Typically, warmup is run and then we start measuring.
# We'll do:
# if warmup > 0:
# for _ in range(warmup):
# self.target()
# Then we start measuring.
# But note: the child process is separate, so the warmup is in the child process.
# We'll do the warmup and then the test.
# However, we want to measure the resource usage during the test only, so we set the start resources after warmup.
# Steps in child:
# 1. Warmup (if any)
for _ in range(self.warmup):
self.target()
# 2. Start measuring
import time
import psutil
process = psutil.Process()
start_time = time.perf_counter()
start_cpu = process.cpu_times()
start_mem = process.memory_info().rss
# Determine the test mode
if self.iterations is not None:
# fixed iterations
total_function_time = 0.0
for i in range(self.iterations):
op_start = time.perf_counter()
self.target()
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
end_time = time.perf_counter()
total_wall_time = end_time - start_time
iterations = self.iterations
else:
# fixed duration
end_time = start_time + self.duration
i = 0
total_function_time = 0.0
while True:
now = time.perf_counter()
if now >= end_time:
break
op_start = now
self.target()
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
i += 1
iterations = i
total_wall_time = end_time - start_time # intended duration
end_cpu = process.cpu_times()
end_mem = process.memory_info().rss
result = {
'iterations': iterations,
'total_function_time': total_function_time,
'total_wall_time': total_wall_time,
'start_user_cpu': start_cpu.user,
'start_system_cpu': start_cpu.system,
'start_mem_rss': start_mem,
'end_user_cpu': end_cpu.user,
'end_system_cpu': end_cpu.system,
'end_mem_rss': end_mem,
}
result_queue.put(result)
# Start the child process
child_proc = multiprocessing.Process(target=child_func)
child_proc.start()
child_proc.join()
# Get the result
if not result_queue.empty():
result = result_queue.get()
else:
raise RuntimeError("Child process did not return a result")
# Compute the metrics
throughput = result['iterations'] / result['total_wall_time']
avg_latency = result['total_function_time'] / result['iterations'] if result['iterations'] > 0 else 0
total_cpu_time = (result['end_user_cpu'] - result['start_user_cpu']) + (result['end_system_cpu'] - result['start_system_cpu'])
avg_cpu_percent = (total_cpu_time / result['total_wall_time']) * 100
memory_used = result['end_mem_rss'] - result['start_mem_rss']
return {
'throughput': throughput,
'avg_latency': avg_latency,
'min_latency': None, # we didn't record min, but we could if we stored all latencies? But that would be memory intensive.
'max_latency': None,
'total_operations': result['iterations'],
'total_time': result['total_wall_time'],
'avg_cpu_percent': avg_cpu_percent,
'memory_used': memory_used,
}
import multiprocessing
import time
import psutil
class PerfTestHarness:
def __init__(self, target, duration=None, iterations=None, warmup=0, *args, **kwargs):
self.target = target
self.args = args
self.kwargs = kwargs
self.duration = duration
self.iterations = iterations
self.warmup = warmup
if duration is None and iterations is None:
raise ValueError("Either duration or iterations must be provided")
if duration is not None and iterations is not None:
raise ValueError("Only one of duration or iterations should be provided")
def run(self):
result_queue = multiprocessing.Queue()
def child_func():
# Warmup
for _ in range(self.warmup):
self.target(*self.args, **self.kwargs)
import time
import psutil
process = psutil.Process()
start_time = time.perf_counter()
start_cpu = process.cpu_times()
start_mem = process.memory_info().rss
if self.iterations is not None:
total_function_time = 0.0
for i in range(self.iterations):
op_start = time.perf_counter()
self.target(*self.args, **self.kwargs)
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
end_time = time.perf_counter()
total_wall_time = end_time - start_time
iterations = self.iterations
else:
end_time = start_time + self.duration
i = 0
total_function_time = 0.0
while True:
now = time.perf_counter()
if now >= end_time:
break
op_start = now
self.target(*self.args, **self.kwargs)
op_end = time.perf_counter()
total_function_time += (op_end - op_start)
i += 1
iterations = i
total_wall_time = end_time - start_time # intended duration
end_cpu = process.cpu_times()
end_mem = process.memory_info().rss
result = {
'iterations': iterations,
'total_function_time': total_function_time,
'total_wall_time': total_wall_time,
'start_user_cpu': start_cpu.user,
'start_system_cpu': start_cpu.system,
'start_mem_rss': start_mem,
'end_user_cpu': end_cpu.user,
'end_system_cpu': end_cpu.system,
'end_mem_rss': end_mem,
}
result_queue.put(result)
child_proc = multiprocessing.Process(target=child_func)
child_proc.start()
child_proc.join()
if not result_queue.empty():
result = result_queue.get()
else:
raise RuntimeError("Child process did not return a result")
throughput = result['iterations'] / result['total_wall_time'] if result['total_wall_time'] > 0 else 0
avg_latency = result['total_function_time'] / result['iterations'] if result['iterations'] > 0 else 0
total_cpu_time = (result['end_user_cpu'] - result['start_user_cpu']) + (result['end_system_cpu'] - result['start_system_cpu'])
avg_cpu_percent = (total_cpu_time / result['total_wall_time']) * 100 if result['total_wall_time'] > 0 else 0
memory_used = result['end_mem_rss'] - result['start_mem_rss']
return {
'throughput': throughput,
'avg_latency': avg_latency,
'total_operations': result['iterations'],
'total_time': result['total_wall_time'],
'avg_cpu_percent': avg_cpu_percent,
'memory_used': memory_used,
}
#!/usr/bin/env python3
"""
Baseline Performance Test Harness
Measures latency, throughput, and system resource profiles
"""
import time
import statistics
import json
import sys
import argparse
import tracemalloc
import psutil
import os
from datetime import datetime
from typing import Callable, Dict, List, Any, Optional
from dataclasses import dataclass, asdict
from concurrent.futures import ThreadPoolExecutor, as_completed
import gc
@dataclass
class LatencyMetrics:
"""Latency measurement results"""
min: float
max: float
mean: float
median: float
p95: float
p99: float
stddev: float
samples: int
@dataclass
class ThroughputMetrics:
"""Throughput measurement results"""
operations_per_second: float
total_operations: int
total_time: float
concurrency: int
@dataclass
class ResourceProfile:
"""System resource usage profile"""
peak_memory_mb: float
avg_memory_mb: float
peak_cpu_percent: float
avg_cpu_percent: float
context_switches: int
thread_count: int
@dataclass
class PerformanceReport:
"""Complete performance test report"""
timestamp: str
test_name: str
latency: LatencyMetrics
throughput: ThroughputMetrics
resources: ResourceProfile
metadata: Dict[str, Any]
raw_latencies: List[float] = None # Optional storage of raw samples
class PerformanceHarness:
"""Main performance testing harness"""
def __init__(
self,
test_name: str = "baseline_test",
warmup_iterations: int = 10,
measurement_iterations: int = 1000,
concurrency: int = 1,
time_based: bool = False,
duration_seconds: float = 10.0
):
"""
Initialize performance harness
Args:
test_name: Name identifier for this test
warmup_iterations: Number of warmup runs (not measured)
measurement_iterations: Number of measured iterations (if not time_based)
concurrency: Number of concurrent workers
time_based: If True, run for duration_seconds instead of fixed iterations
duration_seconds: Duration for time-based testing
"""
self.test_name = test_name
self.warmup_iterations = warmup_iterations
self.measurement_iterations = measurement_iterations
self.concurrency = concurrency
self.time_based = time_based
self.duration_seconds = duration_seconds
# Resource monitoring
self.process = psutil.Process(os.getpid())
self.resource_samples = []
self.memory_traces = []
def measure_latency(
self,
func: Callable,
*args,
**kwargs
) -> LatencyMetrics:
"""
Measure latency of a function
Returns:
LatencyMetrics object with statistical analysis
"""
latencies = []
# Warmup
for _ in range(self.warmup_iterations):
func(*args, **kwargs)
gc.collect() # Clean up between runs
# Actual measurement
if self.time_based:
start_time = time.perf_counter()
count = 0
while time.perf_counter() - start_time < self.duration_seconds:
op_start = time.perf_counter()
func(*args, **kwargs)
op_end = time.perf_counter()
latencies.append((op_end - op_start) * 1000) # Convert to ms
count += 1
self.measurement_iterations = count
else:
for _ in range(self.measurement_iterations):
op_start = time.perf_counter()
func(*args, **kwargs)
op_end = time.perf_counter()
latencies.append((op_end - op_start) * 1000) # Convert to ms
gc.collect() # Optional: force GC to measure consistent conditions
if not latencies:
return LatencyMetrics(0, 0, 0, 0, 0, 0, 0, 0)
sorted_latencies = sorted(latencies)
n = len(latencies)
return LatencyMetrics(
min=min(latencies),
max=max(latencies),
mean=statistics.mean(latencies),
median=statistics.median(latencies),
p95=sorted_latencies[int(n * 0.95)],
p99=sorted_latencies[int(n * 0.99)],
stddev=statistics.stdev(latencies) if n > 1 else 0,
samples=n
)
def measure_throughput(
self,
func: Callable,
*args,
**kwargs
) -> ThroughputMetrics:
"""
Measure throughput (operations per second)
"""
if self.concurrency == 1:
# Single-threaded measurement
if self.time_based:
start = time.perf_counter()
count = 0
while time.perf_counter() - start < self.duration_seconds:
func(*args, **kwargs)
count += 1
total_time = time.perf_counter() - start
else:
start = time.perf_counter()
for _ in range(self.measurement_iterations):
func(*args, **kwargs)
total_time = time.perf_counter() - start
count = self.measurement_iterations
ops_per_sec = count / total_time if total_time > 0 else 0
return ThroughputMetrics(
operations_per_second=ops_per_sec,
total_operations=count,
total_time=total_time,
concurrency=1
)
else:
# Multi-threaded measurement
if self.time_based:
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=self.concurrency) as executor:
futures = []
while time.perf_counter() - start < self.duration_seconds:
futures.append(
executor.submit(func, *args, **kwargs)
)
# Wait for all to complete
for future in as_completed(futures):
try:
future.result()
except Exception as e:
print(f"Error in worker: {e}")
total_time = time.perf_counter() - start
count = len(futures)
else:
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=self.concurrency) as executor:
futures = [
executor.submit(func, *args, **kwargs)
for _ in range(self.measurement_iterations)
]
for future in as_completed(futures):
try:
future.result()
except Exception as e:
print(f"Error in worker: {e}")
total_time = time.perf_counter() - start
count = len(futures)
ops_per_sec = count / total_time if total_time > 0 else 0
return ThroughputMetrics(
operations_per_second=ops_per_sec,
total_operations=count,
total_time=total_time,
concurrency=self.concurrency
)
def profile_resources(self, duration: float = None) -> ResourceProfile:
"""
Profile system resources during operation
Args:
duration: How long to profile (None = until next call to profile_resources)
"""
if duration is None:
# Sample current state
mem_info = self.process.memory_info()
cpu_percent = self.process.cpu_percent(interval=0.1)
return ResourceProfile(
peak_memory_mb=mem_info.rss / 1024 / 1024,
avg_memory_mb=mem_info.rss / 1024 / 1024,
peak_cpu_percent=cpu_percent,
avg_cpu_percent=cpu_percent,
context_switches=self.process.num_ctx_switches().voluntary +
self.process.num_ctx_switches().involuntary,
thread_count=self.process.num_threads()
)
else:
# Continuous profiling for duration
memory_samples = []
cpu_samples = []
start_time = time.perf_counter()
while time.perf_counter() - start_time < duration:
mem_info = self.process.memory_info()
memory_samples.append(mem_info.rss / 1024 / 1024) # Convert to MB
cpu = self.process.cpu_percent(interval=0.1)
if cpu is not None: # cpu_percent can return None first call
cpu_samples.append(cpu)
time.sleep(0.1) # Sample every 100ms
# Also get final memory
final_mem = self.process.memory_info().rss / 1024 / 1024
memory_samples.append(final_mem)
return ResourceProfile(
peak_memory_mb=max(memory_samples) if memory_samples else 0,
avg_memory_mb=statistics.mean(memory_samples) if memory_samples else 0,
peak_cpu_percent=max(cpu_samples) if cpu_samples else 0,
avg_cpu_percent=statistics.mean(cpu_samples) if cpu_samples else 0,
context_switches=self.process.num_ctx_switches().voluntary +
self.process.num_ctx_switches().involuntary,
thread_count=self.process.num_threads()
)
def run_full_test(
self,
func: Callable,
*args,
profile_duration: float = None,
store_raw_latencies: bool = False,
**kwargs
) -> PerformanceReport:
"""
Run complete performance test (latency + throughput + profiling)
Args:
func: Function to test
profile_duration: How long to profile resources (None = profile during test)
store_raw_latencies: Whether to store all raw latency samples in report
"""
print(f"Starting performance test: {self.test_name}")
print(f"Configuration: concurrency={self.concurrency}, "
f"warmup={self.warmup_iterations}, "
f"measurement={'time-based' if self.time_based else 'count-based'}")
# Start memory tracing
tracemalloc.start()
# Measure latency
print("Measuring latency...")
latency_metrics = self.measure_latency(func, *args, **kwargs)
# Measure throughput
print("Measuring throughput...")
throughput_metrics = self.measure_throughput(func, *args, **kwargs)
# Profile resources
print("Profiling resources...")
if profile_duration:
resource_metrics = self.profile_resources(profile_duration)
else:
resource_metrics = self.profile_resources()
# Get memory tracing snapshot
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
# Stop memory tracing
tracemalloc.stop()
# Prepare report
report = PerformanceReport(
timestamp=datetime.now().isoformat(),
test_name=self.test_name,
latency=latency_metrics,
throughput=throughput_metrics,
resources=resource_metrics,
metadata={
'concurrency': self.concurrency,
'warmup_iterations': self.warmup_iterations,
'measurement_iterations': self.measurement_iterations,
'time_based': self.time_based,
'duration_seconds': self.duration_seconds,
'memory_tracing': {
'total_allocated': sum(stat.size for stat in top_stats) / 1024 / 1024,
'top_allocations': [
{
'file': stat.traceback[0].filename,
'line': stat.traceback[0].lineno,
'size_mb': stat.size / 1024 / 1024,
'count': stat.count
}
for stat in top_stats[:10] # Top 10
]
}
},
raw_latencies=latency_metrics.samples if store_raw_latencies else None
)
return report
def print_report(self, report: PerformanceReport):
"""Print formatted performance report"""
print("\n" + "="*60)
print(f"PERFORMANCE REPORT: {report.test_name}")
print("="*60)
print(f"\nTimestamp: {report.timestamp}")
print("\n--- LATENCY METRICS (ms) ---")
print(f" Samples: {report.latency.samples}")
print(f" Min: {report.latency.min:.4f}")
print(f" Max: {report.latency.max:.4f}")
print(f" Mean: {report.latency.mean:.4f}")
print(f" Median: {report.latency.median:.4f}")
print(f" P95: {report.latency.p95:.4f}")
print(f" P99: {report.latency.p99:.4f}")
print(f" StdDev: {report.latency.stddev:.4f}")
print("\n--- THROUGHPUT ---")
print(f" Operations/sec: {report.throughput.operations_per_second:.2f}")
print(f" Total ops: {report.throughput.total_operations}")
print(f" Total time: {report.throughput.total_time:.4f}s")
print(f" Concurrency: {report.throughput.concurrency}")
print("\n--- RESOURCE PROFILE ---")
print(f" Peak Memory: {report.resources.peak_memory_mb:.2f} MB")
print(f" Avg Memory: {report.resources.avg_memory_mb:.2f} MB")
print(f" Peak CPU: {report.resources.peak_cpu_percent:.1f}%")
print(f" Avg CPU: {report.resources.avg_cpu_percent:.1f}%")
print(f" Context Switches: {report.resources.context_switches}")
print(f" Thread Count: {report.resources.thread_count}")
print("\n--- MEMORY ALLOCATION (Top 10) ---")
for i, alloc in enumerate(report.metadata['memory_tracing']['top_allocations'], 1):
print(f" {i}. {alloc['file']}:{alloc['line']} - {alloc['size_mb']:.2f} MB ({alloc['count']} allocations)")
print("\n--- TEST CONFIGURATION ---")
for key, value in report.metadata.items():
if key != 'memory_tracing':
print(f" {key}: {value}")
print("="*60)
def save_report(self, report: PerformanceReport, filename: str):
"""Save report to JSON file"""
# Convert dataclass to dict
report_dict = {
'timestamp': report.timestamp,
'test_name': report.test_name,
'latency': asdict(report.latency),
'throughput': asdict(report.throughput),
'resources': asdict(report.resources),
'metadata': report.metadata,
'raw_latencies': report.raw_latencies
}
with open(filename, 'w') as f:
json.dump(report_dict, f, indent=2)
print(f"\nReport saved to: {filename}")
def example_function(iterations: int = 1):
"""Example function to test - simple computation"""
result = 0
for i in range(iterations):
result += i * i
return result
def example_io_function():
"""Example I/O bound function"""
time.sleep(0.001) # Simulate I/O
return "done"
def example_memory_function(size_kb: int = 100):
"""Example memory allocation function"""
data = bytearray(size_kb * 1024)
return len(data)
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="Baseline Performance Test Harness",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic latency/throughput test (single-threaded, count-based)
python perf_harness.py --function compute --iterations 1000
# Time-based test with concurrency
python perf_harness.py --function io --duration 10 --concurrency 4
# Memory profiling test
python perf_harness.py --function memory --size 1000 --profile-memory
# Save report to file
python perf_harness.py --function compute --save-report results.json
"""
)
parser.add_argument(
'--function',
choices=['compute', 'io', 'memory'],
default='compute',
help='Example function to test'
)
parser.add_argument(
'--iterations',
type=int,
default=1000,
help='Number of iterations for count-based testing'
)
parser.add_argument(
'--duration',
type=float,
default=10.0,
help='Duration in seconds for time-based testing'
)
parser.add_argument(
'--concurrency',
type=int,
default=1,
help='Number of concurrent workers'
)
parser.add_argument(
'--warmup',
type=int,
default=10,
help='Number of warmup iterations'
)
parser.add_argument(
'--time-based',
action='store_true',
help='Run for fixed duration instead of fixed iterations'
)
parser.add_argument(
'--profile-duration',
type=float,
help='Duration to profile resources separately'
)
parser.add_argument(
'--size',
type=int,
default=100,
help='Size parameter for memory function (KB)'
)
parser.add_argument(
'--save-report',
metavar='FILENAME',
help='Save report to JSON file'
)
parser.add_argument(
'--store-raw',
action='store_true',
help='Store raw latency samples in report'
)
return parser.parse_args()
def main():
"""Main entry point"""
args = parse_args()
# Select function based on argument
if args.function == 'compute':
func = lambda: example_function(100) # Compute 100 iterations
test_name = "compute_test"
elif args.function == 'io':
func = example_io_function
test_name = "io_test"
elif args.function == 'memory':
func = lambda: example_memory_function(args.size)
test_name = f"memory_test_{args.size}KB"
else:
func = example_function
test_name = "default_test"
# Initialize harness
harness = PerformanceHarness(
test_name=test_name,
warmup_iterations=args.warmup,
measurement_iterations=args.iterations,
concurrency=args.concurrency,
time_based=args.time_based,
duration_seconds=args.duration
)
# Run test
try:
report = harness.run_full_test(
func,
profile_duration=args.profile_duration,
store_raw_latencies=args.store_raw
)
# Print report
harness.print_report(report)
# Save report if requested
if args.save_report:
harness.save_report(report, args.save_report)
except KeyboardInterrupt:
print("\n\nTest interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\nError during test: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
# Check dependencies
try:
import psutil
except ImportError:
print("Error: psutil is required. Install with: pip install psutil")
sys.exit(1)
try:
import tracemalloc
except ImportError:
print("Error: tracemalloc is required (Python 3.4+)")
sys.exit(1)
main()