|
| 1 | +"""Compare sequential requests with concurrent SerpApi AsyncClient calls. |
| 2 | +
|
| 3 | +The benchmark uses a local delayed HTTP server. It measures client-side |
| 4 | +concurrency without consuming SerpApi searches or introducing internet and API |
| 5 | +server variance. |
| 6 | +""" |
| 7 | + |
| 8 | +import argparse |
| 9 | +import asyncio |
| 10 | +import json |
| 11 | +import statistics |
| 12 | +import threading |
| 13 | +import time |
| 14 | +from contextlib import contextmanager |
| 15 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 16 | + |
| 17 | +import requests |
| 18 | + |
| 19 | +import serpapi |
| 20 | + |
| 21 | + |
| 22 | +class DelayedJSONHandler(BaseHTTPRequestHandler): |
| 23 | + delay = 0.05 |
| 24 | + |
| 25 | + def do_GET(self): |
| 26 | + time.sleep(self.delay) |
| 27 | + payload = json.dumps({"search_metadata": {"status": "Success"}}).encode() |
| 28 | + self.send_response(200) |
| 29 | + self.send_header("Content-Type", "application/json") |
| 30 | + self.send_header("Content-Length", str(len(payload))) |
| 31 | + self.end_headers() |
| 32 | + self.wfile.write(payload) |
| 33 | + |
| 34 | + def log_message(self, format, *args): |
| 35 | + pass |
| 36 | + |
| 37 | + |
| 38 | +@contextmanager |
| 39 | +def delayed_server(delay): |
| 40 | + DelayedJSONHandler.delay = delay |
| 41 | + server = ThreadingHTTPServer(("127.0.0.1", 0), DelayedJSONHandler) |
| 42 | + thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 43 | + thread.start() |
| 44 | + try: |
| 45 | + host, port = server.server_address |
| 46 | + yield f"http://{host}:{port}" |
| 47 | + finally: |
| 48 | + server.shutdown() |
| 49 | + server.server_close() |
| 50 | + thread.join() |
| 51 | + |
| 52 | + |
| 53 | +def measure_requests(base_url, count): |
| 54 | + session = requests.Session() |
| 55 | + session.trust_env = False |
| 56 | + try: |
| 57 | + started = time.perf_counter() |
| 58 | + for _ in range(count): |
| 59 | + response = session.get(f"{base_url}/search", timeout=10) |
| 60 | + response.raise_for_status() |
| 61 | + return time.perf_counter() - started |
| 62 | + finally: |
| 63 | + session.close() |
| 64 | + |
| 65 | + |
| 66 | +def measure_sync_client(base_url, count): |
| 67 | + client = serpapi.Client(trust_env=False, timeout=10) |
| 68 | + client.BASE_DOMAIN = base_url |
| 69 | + try: |
| 70 | + started = time.perf_counter() |
| 71 | + for index in range(count): |
| 72 | + client.search(q=f"query-{index}") |
| 73 | + return time.perf_counter() - started |
| 74 | + finally: |
| 75 | + client.close() |
| 76 | + |
| 77 | + |
| 78 | +async def measure_async_client(base_url, count): |
| 79 | + client = serpapi.AsyncClient(trust_env=False, timeout=10) |
| 80 | + async with client: |
| 81 | + client.BASE_DOMAIN = base_url |
| 82 | + started = time.perf_counter() |
| 83 | + await asyncio.gather( |
| 84 | + *(client.search(q=f"query-{index}") for index in range(count)) |
| 85 | + ) |
| 86 | + return time.perf_counter() - started |
| 87 | + |
| 88 | + |
| 89 | +def summarize(label, timings): |
| 90 | + median = statistics.median(timings) |
| 91 | + spread = f"{min(timings):.3f}-{max(timings):.3f}s" |
| 92 | + print(f"{label:<29} {median:.3f}s median ({spread})") |
| 93 | + return median |
| 94 | + |
| 95 | + |
| 96 | +def main(): |
| 97 | + parser = argparse.ArgumentParser() |
| 98 | + parser.add_argument("--count", type=int, default=20) |
| 99 | + parser.add_argument("--delay", type=float, default=0.05) |
| 100 | + parser.add_argument("--repeats", type=int, default=3) |
| 101 | + args = parser.parse_args() |
| 102 | + if args.count < 1: |
| 103 | + parser.error("--count must be at least 1") |
| 104 | + if args.delay < 0: |
| 105 | + parser.error("--delay must not be negative") |
| 106 | + if args.repeats < 1: |
| 107 | + parser.error("--repeats must be at least 1") |
| 108 | + |
| 109 | + with delayed_server(args.delay) as base_url: |
| 110 | + requests_timings = [ |
| 111 | + measure_requests(base_url, args.count) for _ in range(args.repeats) |
| 112 | + ] |
| 113 | + sync_timings = [ |
| 114 | + measure_sync_client(base_url, args.count) for _ in range(args.repeats) |
| 115 | + ] |
| 116 | + async_timings = [ |
| 117 | + asyncio.run(measure_async_client(base_url, args.count)) |
| 118 | + for _ in range(args.repeats) |
| 119 | + ] |
| 120 | + |
| 121 | + summarize("requests.Session sequential:", requests_timings) |
| 122 | + sync_median = summarize("serpapi.Client sequential:", sync_timings) |
| 123 | + async_median = summarize("AsyncClient concurrent:", async_timings) |
| 124 | + print(f"async vs sync speedup: {sync_median / async_median:.2f}x") |
| 125 | + |
| 126 | + |
| 127 | +if __name__ == "__main__": |
| 128 | + main() |
0 commit comments