Benchmark pickle unpickling performance and memory usage.
| 225 | |
| 226 | |
| 227 | class PickleBenchmark: |
| 228 | """Benchmark pickle unpickling performance and memory usage.""" |
| 229 | |
| 230 | def __init__(self, obj: Any, protocol: int = 5, iterations: int = 3): |
| 231 | self.obj = obj |
| 232 | self.protocol = protocol |
| 233 | self.iterations = iterations |
| 234 | self.pickle_data = pickle.dumps(obj, protocol=protocol) |
| 235 | self.pickle_size = len(self.pickle_data) |
| 236 | |
| 237 | def benchmark_time(self) -> Dict[str, float]: |
| 238 | """Measure unpickling time over multiple iterations.""" |
| 239 | times = [] |
| 240 | |
| 241 | for _ in range(self.iterations): |
| 242 | start = perf_counter() |
| 243 | result = pickle.loads(self.pickle_data) |
| 244 | elapsed = perf_counter() - start |
| 245 | times.append(elapsed) |
| 246 | |
| 247 | # Verify correctness (first iteration only) |
| 248 | if len(times) == 1: |
| 249 | if result != self.obj: |
| 250 | raise ValueError("Unpickled object doesn't match original!") |
| 251 | |
| 252 | return { |
| 253 | 'mean': statistics.mean(times), |
| 254 | 'median': statistics.median(times), |
| 255 | 'stdev': statistics.stdev(times) if len(times) > 1 else 0.0, |
| 256 | 'min': min(times), |
| 257 | 'max': max(times), |
| 258 | } |
| 259 | |
| 260 | def benchmark_memory(self) -> int: |
| 261 | """Measure peak memory usage during unpickling.""" |
| 262 | tracemalloc.start() |
| 263 | |
| 264 | # Warmup |
| 265 | pickle.loads(self.pickle_data) |
| 266 | |
| 267 | # Actual measurement |
| 268 | gc.collect() |
| 269 | tracemalloc.reset_peak() |
| 270 | result = pickle.loads(self.pickle_data) |
| 271 | current, peak = tracemalloc.get_traced_memory() |
| 272 | |
| 273 | tracemalloc.stop() |
| 274 | |
| 275 | # Verify correctness |
| 276 | if result != self.obj: |
| 277 | raise ValueError("Unpickled object doesn't match original!") |
| 278 | |
| 279 | return peak |
| 280 | |
| 281 | def run_all(self) -> Dict[str, Any]: |
| 282 | """Run all benchmarks and return comprehensive results.""" |
| 283 | time_stats = self.benchmark_time() |
| 284 | peak_memory = self.benchmark_memory() |
no outgoing calls
no test coverage detected
searching dependent graphs…