File size: 3,902 Bytes
8aa515d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Served latency of a running gaze-lle-p150 server: N sequential POST /predict requests on one keep-alive connection.

    python scripts/bench_http.py --url http://127.0.0.1:20000 --image media/source_1.png --n 1000 --json http.json

Sends the image (base64, as read from disk) with its head boxes (``--boxes``, pixels; default: the 3 faces of
``media/source_1.png``) and ``heatmap_format`` (default ``png``, the server default). Reports p50 / p99 / min / mean
of the client round trip (request build excluded, JSON parse included) and of the server's ``timing_ms`` stages.
Standard library only.
"""
from __future__ import annotations

import argparse
import base64
import http.client
import json
import os
import statistics
import time
import urllib.parse
from pathlib import Path

SAMPLE_BOXES = "116,28,176,104;269,37,301,81;87,57,107,76"


def stats(ts):
    ts = sorted(ts)
    n = len(ts)
    return {"n": n, "p50": statistics.median(ts), "p99": ts[min(n - 1, int(round(0.99 * (n - 1))))],
            "min": ts[0], "max": ts[-1], "mean": statistics.fmean(ts)}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--url", default="http://127.0.0.1:20000")
    ap.add_argument("--image", default="media/source_1.png")
    ap.add_argument("--boxes", default=SAMPLE_BOXES, help="pixels: x1,y1,x2,y2;...")
    ap.add_argument("--heatmap-format", default="png", choices=["png", "npz", "json", "none"])
    ap.add_argument("--n", type=int, default=1000)
    ap.add_argument("--warmup", type=int, default=20)
    ap.add_argument("--json", default=None)
    args = ap.parse_args()

    u = urllib.parse.urlparse(args.url)
    boxes = [[float(v) for v in b.split(",")] for b in args.boxes.split(";")]
    payload = {"image": base64.b64encode(Path(args.image).read_bytes()).decode("ascii"), "bboxes": boxes,
               "bbox_format": "pixels", "heatmap_format": args.heatmap_format}
    body = json.dumps(payload).encode()
    hdr = {"Content-Type": "application/json", "Connection": "keep-alive"}
    conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=600)

    def post():
        conn.request("POST", "/predict", body=body, headers=hdr)
        r = conn.getresponse()
        data = r.read()
        if r.status != 200:
            raise SystemExit(f"HTTP {r.status}: {data[:300]!r}")
        return json.loads(data)

    for _ in range(args.warmup):
        last = post()
    rt, stages = [], {}
    load0 = os.getloadavg()
    for _ in range(args.n):
        t0 = time.perf_counter()
        last = post()
        rt.append((time.perf_counter() - t0) * 1e3)
        for k, v in last.get("timing_ms", {}).items():
            stages.setdefault(k, []).append(float(v))
    conn.close()
    res = {"script": "scripts/bench_http.py", "url": args.url, "image": args.image, "image_bytes": len(Path(args.image).read_bytes()),
           "request_bytes": len(body), "boxes_px": boxes, "heatmap_format": args.heatmap_format, "warmup": args.warmup,
           "client_roundtrip_ms": stats(rt), "server_timing_ms": {k: stats(v) for k, v in stages.items()},
           "loadavg_start": load0, "loadavg_end": os.getloadavg(),
           "last_response": {k: v for k, v in last.items() if k != "predictions"},
           "last_predictions": [{k: v for k, v in p.items() if k not in ("heatmap_png", "heatmap")} for p in last["predictions"]]}
    s = res["client_roundtrip_ms"]
    print(f"client round trip p50 {s['p50']:.2f} p99 {s['p99']:.2f} min {s['min']:.2f} ms (n={s['n']}, "
          f"{len(body)} B request)")
    for k, v in res["server_timing_ms"].items():
        print(f"  server {k:<10} p50 {v['p50']:.2f} p99 {v['p99']:.2f} ms")
    if args.json:
        Path(args.json).write_text(json.dumps(res, indent=1))


if __name__ == "__main__":
    main()