-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbenchmark.py
More file actions
executable file
·1865 lines (1561 loc) · 67.7 KB
/
benchmark.py
File metadata and controls
executable file
·1865 lines (1561 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Comprehensive HTTP Library Benchmark
Tests ALL libraries across ALL dimensions:
- Sync vs Async
- Sequential vs Concurrent
- Local vs Remote
- HTTP vs HTTPS
- HTTP/1.1 vs HTTP/2
- Proxy HTTP vs Proxy HTTPS
Libraries tested:
- httpmorph (sync + async + HTTP/2) - 19 tests
- httpx (sync + async + HTTP/2) - 19 tests
- requests (sync only) - 9 tests
- aiohttp (async only) - 4 tests
- urllib3 (sync only) - 9 tests
- urllib (sync only) - 9 tests
- pycurl (sync + HTTP/2) - 12 tests
- curl_cffi (sync + HTTP/2) - 12 tests
"""
import json
import os
import platform
import sys
import threading
import time
from datetime import datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
# Optional imports for graphics
try:
import matplotlib
matplotlib.use("Agg") # Non-interactive backend
import matplotlib.pyplot as plt
import numpy as np
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
# Add script directory to sys.path for libs imports
sys.path.insert(0, str(Path(__file__).parent))
# Load environment variables
try:
from dotenv import load_dotenv
env_path = Path(__file__).parent.parent / ".env"
if env_path.exists():
load_dotenv(env_path)
except ImportError:
pass
# Import library benchmark classes (after sys.path modification)
from libs.aiohttp_bench import AiohttpBenchmark # noqa: E402
from libs.curl_cffi_bench import CurlCffiBenchmark # noqa: E402
from libs.httpmorph_bench import HttpmorphBenchmark # noqa: E402
from libs.httpx_bench import HttpxBenchmark # noqa: E402
from libs.pycurl_bench import PycurlBenchmark # noqa: E402
from libs.requests_bench import RequestsBenchmark # noqa: E402
from libs.urllib3_bench import Urllib3Benchmark # noqa: E402
from libs.urllib_bench import UrllibBenchmark # noqa: E402
def get_system_info():
"""Collect system information for benchmark metadata"""
info = {
"os": platform.system(),
"os_version": platform.version(),
"platform": platform.platform(),
"processor": platform.processor() or platform.machine(),
"python_version": sys.version.split()[0],
"python_implementation": platform.python_implementation(),
}
# Try to get CPU count
try:
import multiprocessing
info["cpu_count"] = multiprocessing.cpu_count()
except Exception:
info["cpu_count"] = "unknown"
# Try to get memory info (Unix-like systems)
try:
import subprocess
if platform.system() == "Darwin": # macOS
result = subprocess.run(
["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=1
)
if result.returncode == 0:
mem_bytes = int(result.stdout.strip())
info["memory_gb"] = round(mem_bytes / (1024**3), 2)
elif platform.system() == "Linux":
with open("/proc/meminfo") as f:
for line in f:
if line.startswith("MemTotal:"):
mem_kb = int(line.split()[1])
info["memory_gb"] = round(mem_kb / (1024**2), 2)
break
except Exception:
info["memory_gb"] = "unknown"
return info
# Simple HTTP server
class SimpleHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"OK")
def log_message(self, _format, *_args):
pass
class BenchmarkServer:
def __init__(self, port=18891):
self.port = port
self.server = HTTPServer(("127.0.0.1", port), SimpleHTTPHandler)
self.thread = None
def start(self):
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
time.sleep(0.5)
def stop(self):
self.server.shutdown()
if self.thread:
self.thread.join(timeout=2)
class Benchmark:
def __init__(self, num_sequential=50, warmup=5, num_concurrent=25, concurrent_workers=10):
self.num_sequential = num_sequential
self.warmup = warmup
self.num_concurrent = num_concurrent
self.concurrent_workers = concurrent_workers
self.local_port = 18891
self.local_url = f"http://127.0.0.1:{self.local_port}/"
# Use TEST_HTTPBIN_HOST from .env, fallback to httpbin.org
httpbin_host = os.environ.get("TEST_HTTPBIN_HOST", "httpbin.org")
self.remote_http_url = f"http://{httpbin_host}/get"
self.remote_https_url = f"https://{httpbin_host}/get"
self.http2_url = f"https://{httpbin_host}/get"
# Proxy configuration - separate proxies for HTTP and HTTPS targets
self.proxy_url_http = os.environ.get("TEST_PROXY_URL")
self.proxy_url_https = os.environ.get("TEST_PROXY_URL")
# Fallback to TEST_PROXY_URL if separate proxies not configured
if not self.proxy_url_http:
self.proxy_url_http = os.environ.get("TEST_PROXY_URL")
if not self.proxy_url_https:
self.proxy_url_https = os.environ.get("TEST_PROXY_URL")
self.proxy_target_http = f"http://{httpbin_host}/get" # HTTP target via proxy
self.proxy_target_https = f"https://{httpbin_host}/get" # HTTPS target via proxy
self.results = {}
# Create config dict for library benchmarks
config = {
"num_sequential": num_sequential,
"num_concurrent": num_concurrent,
"concurrent_workers": concurrent_workers,
"warmup_requests": warmup,
"local_url": self.local_url,
"remote_http_url": self.remote_http_url,
"remote_https_url": self.remote_https_url,
"http2_url": self.http2_url,
"proxy_url_http": self.proxy_url_http,
"proxy_url_https": self.proxy_url_https,
"proxy_target_http": self.proxy_target_http,
"proxy_target_https": self.proxy_target_https,
}
# Initialize library benchmarks
self.lib_benchmarks = {
"httpmorph": HttpmorphBenchmark(config),
"requests": RequestsBenchmark(config),
"httpx": HttpxBenchmark(config),
"aiohttp": AiohttpBenchmark(config),
"urllib3": Urllib3Benchmark(config),
"urllib": UrllibBenchmark(config),
"pycurl": PycurlBenchmark(config),
"curl_cffi": CurlCffiBenchmark(config),
}
self.library_versions = {}
def get_library_versions(self):
"""Detect and return versions of all available libraries"""
versions = {}
# httpmorph
try:
import httpmorph
versions["httpmorph"] = (
httpmorph.__version__ if hasattr(httpmorph, "__version__") else "unknown"
)
except ImportError:
versions["httpmorph"] = "not installed"
# requests
try:
import requests
versions["requests"] = requests.__version__
except ImportError:
versions["requests"] = "not installed"
# httpx
try:
import httpx
versions["httpx"] = httpx.__version__
except ImportError:
versions["httpx"] = "not installed"
# aiohttp
try:
import aiohttp
versions["aiohttp"] = aiohttp.__version__
except ImportError:
versions["aiohttp"] = "not installed"
# urllib3
try:
import urllib3
versions["urllib3"] = urllib3.__version__
except ImportError:
versions["urllib3"] = "not installed"
# urllib (built-in, use Python version)
versions["urllib"] = f"built-in (Python {sys.version.split()[0]})"
# pycurl
try:
import pycurl
versions["pycurl"] = pycurl.version
except ImportError:
versions["pycurl"] = "not installed"
# curl_cffi
try:
import curl_cffi
versions["curl_cffi"] = (
curl_cffi.__version__ if hasattr(curl_cffi, "__version__") else "unknown"
)
except ImportError:
versions["curl_cffi"] = "not installed"
return versions
def run_all(self, lib_filter=None, generate_graphics=True):
"""Run all benchmarks
Args:
lib_filter: List of library names to test (None = all libraries)
generate_graphics: Whether to generate graphics (default: True)
"""
# Get library versions
self.library_versions = self.get_library_versions()
print("=" * 120)
print("COMPREHENSIVE HTTP LIBRARY BENCHMARK")
print("=" * 120)
print(f"Sequential requests: {self.num_sequential} (warmup: {self.warmup})")
print(f"Concurrent requests: {self.num_concurrent} (workers: {self.concurrent_workers})")
if self.proxy_url_http or self.proxy_url_https:
if self.proxy_url_http:
proxy_display_http = (
self.proxy_url_http.split("@")[-1]
if "@" in self.proxy_url_http
else self.proxy_url_http
)
print(f"Proxy HTTP configured: {proxy_display_http}")
if self.proxy_url_https:
proxy_display_https = (
self.proxy_url_https.split("@")[-1]
if "@" in self.proxy_url_https
else self.proxy_url_https
)
print(f"Proxy HTTPS configured: {proxy_display_https}")
else:
print("Proxy: Not configured")
if lib_filter:
print(f"Testing only: {', '.join(lib_filter)}")
print("-" * 120)
print("Library Versions:")
for lib_name in [
"httpmorph",
"requests",
"httpx",
"aiohttp",
"urllib3",
"urllib",
"pycurl",
"curl_cffi",
]:
version = self.library_versions.get(lib_name, "unknown")
status = "[OK]" if version not in ["not installed", "unknown"] else "[--]"
print(f" {status} {lib_name:<12} {version}")
print("=" * 120)
print()
# Start local server
print("Starting local HTTP server...")
server = BenchmarkServer(self.local_port)
server.start()
# Run tests for each library
for lib_name, lib_bench in self.lib_benchmarks.items():
# Skip if library filter is specified and this library is not in it
if lib_filter and lib_name not in lib_filter:
continue
# Check if library is available
if not lib_bench.is_available():
print(f"\n[{lib_name}] Not installed - SKIPPED")
continue
print(f"\n{'=' * 120}")
print(f"Testing: {lib_name}")
print("=" * 120)
if lib_name not in self.results:
self.results[lib_name] = {}
# Get test matrix from library benchmark
tests = lib_bench.get_test_matrix()
for test_name, test_key in tests:
# Check if method exists
if not hasattr(lib_bench, test_key):
continue
try:
print(f" {test_name:<30} ", end="", flush=True)
method = getattr(lib_bench, test_key)
result = method()
self.results[lib_name][test_key] = result
if "error" in result:
print(f"ERROR: {result['error']}")
elif "mean_ms" in result:
# Sequential result
print(f"{result['mean_ms']:>8.2f}ms (median: {result['median_ms']:.2f}ms)")
elif "req_per_sec" in result:
# Concurrent result
print(
f"{result['req_per_sec']:>8.2f} req/s (avg: {result['avg_ms']:.2f}ms)"
)
else:
print("OK")
except Exception as e:
error_msg = f"{type(e).__name__}: {str(e)[:50]}"
self.results[lib_name][test_key] = {"error": error_msg}
print(f"ERROR: {error_msg}")
server.stop()
# Print summary
self.print_summary()
# Export results
self.export_results(generate_graphics=generate_graphics)
return self.results
def print_summary(self):
"""Print comprehensive summary"""
print("\n" + "=" * 120)
print("SUMMARY - PERFORMANCE COMPARISON")
print("=" * 120)
# Sequential tests summary
print("\nSEQUENTIAL TESTS (Mean Response Time)")
print("-" * 120)
print(f"{'Library':<15} {'Local':<12} {'HTTPS':<12} {'HTTP/2':<12} {'Proxy':<12}")
print("-" * 120)
for lib in ["httpmorph", "requests", "httpx", "urllib3"]:
if lib not in self.results:
continue
row = f"{lib:<15}"
for key in ["seq_local", "seq_https", "seq_http2", "seq_proxy"]:
if key in self.results[lib] and "mean_ms" in self.results[lib][key]:
row += f" {self.results[lib][key]['mean_ms']:>9.2f}ms"
else:
row += f" {'N/A':>11}"
print(row)
# Concurrent tests summary
print("\nCONCURRENT TESTS (Throughput)")
print("-" * 120)
print(f"{'Library':<15} {'Local':<15} {'HTTPS':<15} {'Proxy':<15}")
print("-" * 120)
for lib in ["httpmorph", "requests", "httpx", "urllib3"]:
if lib not in self.results:
continue
row = f"{lib:<15}"
for key in ["conc_local", "conc_https", "conc_proxy"]:
if key in self.results[lib] and "req_per_sec" in self.results[lib][key]:
row += f" {self.results[lib][key]['req_per_sec']:>9.2f} req/s"
else:
row += f" {'N/A':>14}"
print(row)
# Async tests summary
print("\nASYNC TESTS (Throughput)")
print("-" * 120)
print(f"{'Library':<15} {'Local':<15} {'HTTPS':<15} {'Proxy':<15}")
print("-" * 120)
for lib in ["httpmorph", "httpx", "aiohttp"]:
if lib not in self.results:
continue
row = f"{lib:<15}"
for key in ["async_local", "async_https", "async_proxy"]:
if key in self.results[lib] and "req_per_sec" in self.results[lib][key]:
row += f" {self.results[lib][key]['req_per_sec']:>9.2f} req/s"
else:
row += f" {'N/A':>14}"
print(row)
print("\n" + "=" * 120)
# Winners per category
print("\nWINNERS BY CATEGORY")
print("-" * 120)
categories = {
"Fastest Sequential HTTPS": ("seq_https", "mean_ms", min),
"Highest Concurrent Throughput": ("conc_https", "req_per_sec", max),
"Highest Async Throughput": ("async_https", "req_per_sec", max),
"Best Proxy Performance (Async)": ("async_proxy", "req_per_sec", max),
}
for category_name, (key, metric, comp_func) in categories.items():
values = {}
for lib in self.results:
if key in self.results[lib] and metric in self.results[lib][key]:
values[lib] = self.results[lib][key][metric]
if values:
winner_lib = comp_func(values.items(), key=lambda x: x[1])
winner_value = winner_lib[1]
unit = "ms" if metric.endswith("_ms") else "req/s"
print(f"{category_name:<35}: {winner_lib[0]:<15} ({winner_value:.2f} {unit})")
print("=" * 120)
def export_results(self, generate_graphics=True):
"""Export results to JSON and Markdown
Args:
generate_graphics: Whether to generate graphics (default: True)
"""
# Get version from pyproject.toml
version = "unknown"
try:
pyproject_path = Path(__file__).parent.parent / "pyproject.toml"
if pyproject_path.exists():
with open(pyproject_path) as f:
for line in f:
if line.strip().startswith("version"):
version = line.split("=")[1].strip().strip("\"'")
break
except Exception:
pass
# Create directory structure: results/<os>/<version>/
os_name = platform.system().lower()
results_dir = Path(__file__).parent / "results"
os_dir = results_dir / os_name
version_dir = os_dir / version
version_dir.mkdir(parents=True, exist_ok=True)
# Use fixed filenames: benchmark.json / benchmark.md (no timestamp)
json_file = version_dir / "benchmark.json"
md_file = version_dir / "benchmark.md"
# Load existing results if they exist (for merge during retest)
existing_results = {}
if json_file.exists():
try:
with open(json_file) as f:
existing_data = json.load(f)
existing_results = existing_data.get("results", {})
print(f"\nLoading existing results from {json_file}")
print(f" Found results for: {', '.join(existing_results.keys())}")
except Exception as e:
print(f"\n[WARNING] Could not load existing results: {e}")
# Merge existing results with new results (new results overwrite)
merged_results = existing_results.copy()
for lib_name, lib_data in self.results.items():
if lib_name not in merged_results:
merged_results[lib_name] = {}
merged_results[lib_name].update(lib_data)
# Collect system information
system_info = get_system_info()
# Prepare export data
export_data = {
"metadata": {
"timestamp": datetime.now().isoformat(),
"version": version,
"num_sequential": self.num_sequential,
"num_concurrent": self.num_concurrent,
"concurrent_workers": self.concurrent_workers,
"warmup_requests": self.warmup,
"library_versions": self.library_versions, # Add library versions
**system_info, # Add all system info
},
"results": merged_results,
}
# Export JSON: results/<os>/<version>/benchmark.json
with open(json_file, "w") as f:
json.dump(export_data, f, indent=2)
# Export Markdown: results/<os>/<version>/benchmark.md
self._export_markdown(md_file, export_data)
# Generate graphics if matplotlib is available and requested
if MATPLOTLIB_AVAILABLE and generate_graphics:
graphics_dir = version_dir / "graphics"
graphics_dir.mkdir(exist_ok=True)
# Use "latest" as identifier instead of timestamp
self._generate_graphics(export_data, graphics_dir, "latest")
print(f"\nGraphics generated: {graphics_dir}/*.png")
# Analyze within-benchmark trends (only for newly tested libraries)
trend_data = self._analyze_trends()
if trend_data:
print("\nWithin-Benchmark Trends:")
for lib_name, lib_trends in trend_data.items():
print(f" {lib_name}:")
for test_name, trend in lib_trends.items():
print(f" {test_name}: {trend}")
print("\nResults exported to:")
print(f" {json_file}")
print(f" {md_file}")
def _analyze_trends(self) -> dict:
"""Analyze within-benchmark performance trends with detailed metrics"""
trends = {}
try:
for lib_name, lib_results in self.results.items():
lib_trends = {}
for test_name, test_data in lib_results.items():
if "error" in test_data:
continue
# Build detailed trend analysis
trend_info = []
# Linear trend slope
if "trend_slope_ms_per_req" in test_data:
slope = test_data["trend_slope_ms_per_req"]
if abs(slope) > 0.001: # Significant trend
if slope > 0:
trend_info.append(f"UP +{slope:.4f}ms/req")
else:
trend_info.append(f"DOWN {slope:.4f}ms/req")
else:
trend_info.append(f"Stable ({slope:+.5f}ms/req)")
# Coefficient of variation (stability)
if "cv_pct" in test_data:
cv = test_data["cv_pct"]
if cv < 5:
stability = "Very Stable"
elif cv < 15:
stability = "Stable"
elif cv < 30:
stability = "Moderate"
else:
stability = "Variable"
trend_info.append(f"CV: {cv:.1f}% ({stability})")
# Quartile progression
if all(
k in test_data for k in ["q1_avg_ms", "q2_avg_ms", "q3_avg_ms", "q4_avg_ms"]
):
q1, q2, q3, q4 = (
test_data["q1_avg_ms"],
test_data["q2_avg_ms"],
test_data["q3_avg_ms"],
test_data["q4_avg_ms"],
)
trend_info.append(f"Q1-Q4: {q1:.2f}-{q2:.2f}-{q3:.2f}-{q4:.2f}ms")
# Percentiles for sequential tests
if "p95_ms" in test_data and "p99_ms" in test_data:
trend_info.append(
f"P95: {test_data['p95_ms']:.2f}ms, P99: {test_data['p99_ms']:.2f}ms"
)
if trend_info:
lib_trends[test_name] = " | ".join(trend_info)
if lib_trends:
trends[lib_name] = lib_trends
except Exception as e:
print(f"\n[WARNING] Trend analysis failed: {e}")
return trends
def _generate_graphics(self, data: dict, graphics_dir: Path, timestamp: str):
"""Generate performance comparison graphics"""
if not MATPLOTLIB_AVAILABLE:
return
results = data["results"]
# 1. Sequential Performance - All Scenarios
self._plot_sequential_comparison(results, graphics_dir, timestamp)
# 2. Concurrent Performance - All Scenarios
self._plot_concurrent_comparison(results, graphics_dir, timestamp)
# 3. Async Performance - All Scenarios
self._plot_async_comparison(results, graphics_dir, timestamp)
# 4. HTTP/2 Performance
self._plot_http2_comparison(results, graphics_dir, timestamp)
# 5. Stability Comparison (CV%)
self._plot_stability_comparison(results, graphics_dir, timestamp)
# 6. Trend Analysis (Slope)
self._plot_trend_comparison(results, graphics_dir, timestamp)
# 7. Proxy Performance
self._plot_proxy_comparison(results, graphics_dir, timestamp)
# 8. Performance Heatmap
self._plot_performance_heatmap(results, graphics_dir, timestamp)
# 9. Overall Speed Ranking
self._plot_overall_ranking(results, graphics_dir, timestamp)
def _plot_sequential_comparison(self, results: dict, graphics_dir: Path, timestamp: str):
"""Plot sequential request performance comparison - ALL scenarios"""
all_libs = [
"httpmorph",
"requests",
"httpx",
"urllib3",
"urllib",
"aiohttp",
"pycurl",
"curl_cffi",
]
scenarios = [
("seq_local_http", "Local HTTP", "#4CAF50"),
("seq_remote_http", "Remote HTTP", "#2196F3"),
("seq_remote_https", "Remote HTTPS", "#9C27B0"),
("seq_proxy_http", "Proxy HTTP", "#FF9800"),
]
libs = []
data_by_scenario = {s[0]: [] for s in scenarios}
for lib_name in all_libs:
if lib_name not in results:
continue
has_data = False
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("mean_ms")
if val and not results[lib_name].get(scenario_key, {}).get("error"):
has_data = True
if has_data:
libs.append(lib_name)
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("mean_ms")
data_by_scenario[scenario_key].append(val if val else 0)
if not libs:
return
fig, ax = plt.subplots(figsize=(14, 7))
x = range(len(libs))
width = 0.2
for idx, (scenario_key, label, color) in enumerate(scenarios):
offset = (idx - len(scenarios) / 2 + 0.5) * width
bars = ax.bar(
[i + offset for i in x],
data_by_scenario[scenario_key],
width,
label=label,
color=color,
)
# Add value labels on top of bars
for bar in bars:
height = bar.get_height()
if height > 0:
ax.text(
bar.get_x() + bar.get_width() / 2.0,
height,
f"{height:.1f}",
ha="center",
va="bottom",
fontsize=7,
)
ax.set_ylabel("Response Time (ms)", fontsize=11)
ax.set_title(
"Sequential Performance - All Scenarios (Lower is Better)",
fontsize=13,
fontweight="bold",
)
ax.set_xticks(x)
ax.set_xticklabels(libs, rotation=45, ha="right")
ax.legend(loc="upper left", fontsize=9)
ax.grid(True, alpha=0.3, axis="y")
plt.tight_layout()
plt.savefig(graphics_dir / f"01_sequential_all_{timestamp}.png", dpi=150)
plt.close()
def _plot_concurrent_comparison(self, results: dict, graphics_dir: Path, timestamp: str):
"""Plot concurrent throughput comparison - ALL scenarios"""
all_libs = [
"httpmorph",
"requests",
"httpx",
"urllib3",
"urllib",
"aiohttp",
"pycurl",
"curl_cffi",
]
scenarios = [
("conc_local_http", "Local HTTP", "#4CAF50"),
("conc_remote_http", "Remote HTTP", "#2196F3"),
("conc_remote_https", "Remote HTTPS", "#9C27B0"),
("conc_proxy_https", "Proxy HTTPS", "#FF9800"),
]
libs = []
data_by_scenario = {s[0]: [] for s in scenarios}
for lib_name in all_libs:
if lib_name not in results:
continue
has_data = False
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("req_per_sec")
if val and not results[lib_name].get(scenario_key, {}).get("error"):
has_data = True
if has_data:
libs.append(lib_name)
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("req_per_sec")
data_by_scenario[scenario_key].append(val if val else 0)
if not libs:
return
fig, ax = plt.subplots(figsize=(14, 7))
x = range(len(libs))
width = 0.2
for idx, (scenario_key, label, color) in enumerate(scenarios):
offset = (idx - len(scenarios) / 2 + 0.5) * width
bars = ax.bar(
[i + offset for i in x],
data_by_scenario[scenario_key],
width,
label=label,
color=color,
)
# Add value labels
for bar in bars:
height = bar.get_height()
if height > 0:
ax.text(
bar.get_x() + bar.get_width() / 2.0,
height,
f"{height:.0f}",
ha="center",
va="bottom",
fontsize=7,
)
ax.set_ylabel("Throughput (req/s)", fontsize=11)
ax.set_title(
"Concurrent Throughput - All Scenarios (Higher is Better)",
fontsize=13,
fontweight="bold",
)
ax.set_xticks(x)
ax.set_xticklabels(libs, rotation=45, ha="right")
ax.legend(loc="upper left", fontsize=9)
ax.grid(True, alpha=0.3, axis="y")
plt.tight_layout()
plt.savefig(graphics_dir / f"02_concurrent_all_{timestamp}.png", dpi=150)
plt.close()
def _plot_async_comparison(self, results: dict, graphics_dir: Path, timestamp: str):
"""Plot async throughput comparison - ALL scenarios"""
async_libs = ["httpmorph", "httpx", "aiohttp", "curl_cffi"]
scenarios = [
("async_local_http", "Local HTTP", "#4CAF50"),
("async_remote_http", "Remote HTTP", "#2196F3"),
("async_remote_https", "Remote HTTPS", "#9C27B0"),
("async_proxy_https", "Proxy HTTPS", "#FF9800"),
("async_remote_http2", "HTTP/2", "#00BCD4"),
]
libs = []
data_by_scenario = {s[0]: [] for s in scenarios}
for lib_name in async_libs:
if lib_name not in results:
continue
has_data = False
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("req_per_sec")
if val and not results[lib_name].get(scenario_key, {}).get("error"):
has_data = True
if has_data:
libs.append(lib_name)
for scenario_key, _, _ in scenarios:
val = results[lib_name].get(scenario_key, {}).get("req_per_sec")
data_by_scenario[scenario_key].append(val if val else 0)
if not libs:
return
fig, ax = plt.subplots(figsize=(14, 7))
x = range(len(libs))
width = 0.15
for idx, (scenario_key, label, color) in enumerate(scenarios):
offset = (idx - len(scenarios) / 2 + 0.5) * width
bars = ax.bar(
[i + offset for i in x],
data_by_scenario[scenario_key],
width,
label=label,
color=color,
)
# Add value labels
for bar in bars:
height = bar.get_height()
if height > 0:
ax.text(
bar.get_x() + bar.get_width() / 2.0,
height,
f"{height:.0f}",
ha="center",
va="bottom",
fontsize=7,
rotation=90,
)
ax.set_ylabel("Throughput (req/s)", fontsize=11)
ax.set_title(
"Async Performance - All Scenarios (Higher is Better)", fontsize=13, fontweight="bold"
)
ax.set_xticks(x)
ax.set_xticklabels(libs, rotation=45, ha="right")
ax.legend(loc="upper left", fontsize=9, ncol=2)
ax.grid(True, alpha=0.3, axis="y")
plt.tight_layout()
plt.savefig(graphics_dir / f"03_async_all_{timestamp}.png", dpi=150)
plt.close()
def _plot_http2_comparison(self, results: dict, graphics_dir: Path, timestamp: str):
"""Plot HTTP/2 performance comparison"""
libs = []
seq_times = []
conc_throughputs = []
for lib_name in ["httpmorph", "httpx", "pycurl", "curl_cffi"]:
if lib_name not in results:
continue
seq_val = results[lib_name].get("seq_remote_http2", {}).get("mean_ms")
conc_val = results[lib_name].get("conc_remote_http2", {}).get("req_per_sec")
if seq_val or conc_val:
libs.append(lib_name)
seq_times.append(seq_val if seq_val else 0)
conc_throughputs.append(conc_val if conc_val else 0)
if not libs:
return
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
# Sequential HTTP/2
ax1.bar(libs, seq_times, color="#00BCD4")
ax1.set_ylabel("Response Time (ms)")
ax1.set_title("HTTP/2 Sequential Performance (Lower is Better)")
ax1.set_xticklabels(libs, rotation=45, ha="right")
ax1.grid(True, alpha=0.3)
# Concurrent HTTP/2
ax2.bar(libs, conc_throughputs, color="#009688")
ax2.set_ylabel("Throughput (req/s)")
ax2.set_title("HTTP/2 Concurrent Throughput (Higher is Better)")
ax2.set_xticklabels(libs, rotation=45, ha="right")
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(graphics_dir / f"04_http2_{timestamp}.png", dpi=150)
plt.close()
def _plot_time_series(self, results: dict, graphics_dir: Path, timestamp: str):
"""Plot time-series progression for httpmorph tests"""
try:
if "httpmorph" not in results:
return
httpmorph_results = results["httpmorph"]
# Find tests with timing data
test_plots = []
for test_name, test_data in httpmorph_results.items():
if "error" in test_data:
continue
timings = test_data.get("timings") or test_data.get("completion_times")
if timings and len(timings) > 5: # Only plot if we have enough data
test_plots.append((test_name, timings))
if not test_plots:
return
# Plot up to 4 most interesting tests
test_plots = test_plots[:4]
n_plots = len(test_plots)
if n_plots == 1:
fig, axes = plt.subplots(1, 1, figsize=(12, 4))
axes = [axes]
elif n_plots == 2:
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
else:
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
axes = axes.flatten()
for idx, (test_name, timings) in enumerate(test_plots):
ax = axes[idx]
# Plot time series
x = list(range(1, len(timings) + 1))
ax.plot(x, timings, linewidth=1, alpha=0.7, color="#2196F3")
# Add trend line
import numpy as np
z = np.polyfit(x, timings, 1)
p = np.poly1d(z)