Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

python/bench.py

SHA-256 (LF line endings, as in the source ZIP): 264d964307793c871c1ccad93d88928b48970f38d9d590271cb9108f6d837faa · MIT license (the benchmark suite only)

#!/usr/bin/env python3
"""competitive-bench-v1 - the Python baseline (CPython, the standard library only).

    python bench.py --scenario <id> --input <log> [--repeat N] [--output <file>]

prints one JSON line: the result, the time of each in-process repetition (runsMs), the process's CPU time and peak
working set. How it reads: the file opened in binary mode with a 1 MB buffer and iterated line by line (the
idiomatic streaming loop - never read whole); bytes.find for text, split for W3C fields (positions from the #Fields
header), dict counting; strings are decoded only for the keys that are reported. Single-threaded.
"""
import argparse
import ctypes
import ctypes.wintypes
import json
import sys
import time

BUFFER = 1 << 20


def literal_error(path):
    n = 0
    with open(path, 'rb', buffering=BUFFER) as f:
        for line in f:
            if b'ERROR' in line:
                n += 1
    return {'count': n}


def elapsed_ge_1000(path):
    n = 0
    with open(path, 'rb', buffering=BUFFER) as f:
        for line in f:
            at = line.find(b'elapsed: ')
            if at < 0:
                continue
            end = line.find(b'ms', at + 9)
            if end > at + 9 and float(line[at + 9:end]) >= 1000:
                n += 1
    return {'count': n}


class W3C:
    """The records of a W3C extended log, split by spaces; field positions from #Fields."""

    def __init__(self, path):
        self.path = path
        self.index = {}

    def records(self):
        with open(self.path, 'rb', buffering=BUFFER) as f:
            for line in f:
                if line[:1] == b'#':
                    if line.startswith(b'#Fields: '):
                        self.index = {name: i for i, name in enumerate(line[9:].split())}
                    continue
                yield line.split(b' ')


def count_where(path, test):
    log = W3C(path)
    n = 0
    status = taken = None
    for f in log.records():
        if status is None:
            status, taken = log.index[b'sc-status'], log.index[b'time-taken']
        if test(int(f[status]), int(f[taken])):
            n += 1
    return {'count': n}


def top(path, key, status_test, post=False):
    log = W3C(path)
    counts = {}
    matched = 0
    status = k = method = None
    for f in log.records():
        if status is None:
            status, k, method = log.index[b'sc-status'], log.index[key], log.index[b'cs-method']
        if not status_test(int(f[status])):
            continue
        if post and f[method] != b'POST':
            continue
        matched += 1
        v = f[k]
        counts[v] = counts.get(v, 0) + 1
    best = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
    return {'count': matched, 'top': [[k.decode('ascii'), c] for k, c in best]}


def per_minute(path):
    log = W3C(path)
    counts = {}
    status = date = tm = None
    for f in log.records():
        if status is None:
            status, date, tm = log.index[b'sc-status'], log.index[b'date'], log.index[b'time']
        if int(f[status]) < 500:
            continue
        minute = f[date] + b'T' + f[tm][:5]
        counts[minute] = counts.get(minute, 0) + 1
    return {'buckets': [[k.decode('ascii'), c] for k, c in sorted(counts.items())]}


def records(path, output, projected):
    log = W3C(path)
    n = 0
    status = method = None
    with open(output, 'w', encoding='utf-8', newline='\n') as out:
        for f in log.records():
            if status is None:
                status, method = log.index[b'sc-status'], log.index[b'cs-method']
                names = [name.decode('ascii') for name, _ in sorted(log.index.items(), key=lambda kv: kv[1])]
            if int(f[status]) != 503 or f[method] != b'POST':
                continue
            n += 1
            if projected:
                rec = {'time': f[log.index[b'date']].decode() + 'T' + f[log.index[b'time']].decode() + 'Z',
                       'c-ip': f[log.index[b'c-ip']].decode(), 'cs-uri-stem': f[log.index[b'cs-uri-stem']].decode()}
            else:
                rec = {name: f[i].decode().rstrip('\r\n') for i, name in enumerate(names)}
            out.write(json.dumps(rec, separators=(',', ':')))
            out.write('\n')
        size = out.tell()
    return {'count': n, 'bytes': size}


SCENARIOS = {
    'literal-error': lambda p, o: literal_error(p),
    'elapsed-ge-1000': lambda p, o: elapsed_ge_1000(p),
    'count-5xx': lambda p, o: count_where(p, lambda s, t: s >= 500),
    'count-slow': lambda p, o: count_where(p, lambda s, t: t >= 1000),
    'top-ip-5xx': lambda p, o: top(p, b'c-ip', lambda s: s >= 500),
    'top-uri-5xx': lambda p, o: top(p, b'cs-uri-stem', lambda s: s >= 500),
    'top-ip-503-post': lambda p, o: top(p, b'c-ip', lambda s: s == 503, True),
    'per-minute-5xx': lambda p, o: per_minute(p),
    'records-503-post-full': lambda p, o: records(p, o, False),
    'records-503-post-projected': lambda p, o: records(p, o, True),
}


class PROCESS_MEMORY_COUNTERS(ctypes.Structure):
    _fields_ = [('cb', ctypes.wintypes.DWORD), ('PageFaultCount', ctypes.wintypes.DWORD),
                ('PeakWorkingSetSize', ctypes.c_size_t), ('WorkingSetSize', ctypes.c_size_t),
                ('QuotaPeakPagedPoolUsage', ctypes.c_size_t), ('QuotaPagedPoolUsage', ctypes.c_size_t),
                ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t), ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
                ('PagefileUsage', ctypes.c_size_t), ('PeakPagefileUsage', ctypes.c_size_t)]


def peak_working_set():
    counters = PROCESS_MEMORY_COUNTERS()
    counters.cb = ctypes.sizeof(counters)
    kernel32 = ctypes.WinDLL('kernel32')
    kernel32.GetCurrentProcess.restype = ctypes.wintypes.HANDLE
    psapi = ctypes.WinDLL('psapi')
    psapi.GetProcessMemoryInfo.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESS_MEMORY_COUNTERS), ctypes.wintypes.DWORD]
    psapi.GetProcessMemoryInfo(kernel32.GetCurrentProcess(), ctypes.byref(counters), counters.cb)
    return counters.PeakWorkingSetSize


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--scenario', required=True, choices=sorted(SCENARIOS))
    ap.add_argument('--input', required=True)
    ap.add_argument('--repeat', type=int, default=1)
    ap.add_argument('--output')
    a = ap.parse_args()
    runs = []
    result = None
    for _ in range(a.repeat):
        started = time.perf_counter()
        result = SCENARIOS[a.scenario](a.input, a.output)
        runs.append(round((time.perf_counter() - started) * 1000, 3))
    t = time.process_time()
    print(json.dumps({'implementation': 'python', 'runtime': 'CPython ' + sys.version.split()[0], 'scenario': a.scenario,
                      'result': result, 'runsMs': runs, 'cpuMs': round(t * 1000, 1), 'peakWorkingSetBytes': peak_working_set()}))


if __name__ == '__main__':
    main()