|
| 1 | +""" |
| 2 | +Benchmark: pandas category set operations — intersection and difference of |
| 3 | +categorical Series categories (100k-element, 20 categories each). |
| 4 | +Mirrors tsb's catIntersectCategories / catDiffCategories. |
| 5 | +Outputs JSON: {"function": "cat_intersect_diff", "mean_ms": ..., "iterations": ..., "total_ms": ...} |
| 6 | +""" |
| 7 | +import json |
| 8 | +import time |
| 9 | +import pandas as pd |
| 10 | + |
| 11 | +SIZE = 100_000 |
| 12 | +WARMUP = 5 |
| 13 | +ITERATIONS = 30 |
| 14 | + |
| 15 | +cats_a = [f"cat_a_{i}" for i in range(20)] |
| 16 | +cats_b = [f"cat_{'a' if i < 10 else 'b'}_{i}" for i in range(20)] |
| 17 | + |
| 18 | +data_a = [cats_a[i % len(cats_a)] for i in range(SIZE)] |
| 19 | +data_b = [cats_b[i % len(cats_b)] for i in range(SIZE)] |
| 20 | + |
| 21 | +s_a = pd.Categorical(data_a, categories=cats_a) |
| 22 | +s_b = pd.Categorical(data_b, categories=cats_b) |
| 23 | + |
| 24 | +def cat_intersect(a, b): |
| 25 | + """Return new Categorical with categories = intersection of a.categories and b.categories.""" |
| 26 | + b_set = set(b.categories) |
| 27 | + intersected = [c for c in a.categories if c in b_set] |
| 28 | + return pd.Categorical(a, categories=intersected) |
| 29 | + |
| 30 | +def cat_diff(a, b): |
| 31 | + """Return new Categorical with categories = a.categories - b.categories.""" |
| 32 | + b_set = set(b.categories) |
| 33 | + remaining = [c for c in a.categories if c not in b_set] |
| 34 | + return pd.Categorical(a, categories=remaining) |
| 35 | + |
| 36 | +for _ in range(WARMUP): |
| 37 | + cat_intersect(s_a, s_b) |
| 38 | + cat_diff(s_a, s_b) |
| 39 | + |
| 40 | +times = [] |
| 41 | +for _ in range(ITERATIONS): |
| 42 | + t0 = time.perf_counter() |
| 43 | + cat_intersect(s_a, s_b) |
| 44 | + cat_diff(s_a, s_b) |
| 45 | + times.append((time.perf_counter() - t0) * 1000) |
| 46 | + |
| 47 | +total_ms = sum(times) |
| 48 | +print(json.dumps({ |
| 49 | + "function": "cat_intersect_diff", |
| 50 | + "mean_ms": total_ms / ITERATIONS, |
| 51 | + "iterations": ITERATIONS, |
| 52 | + "total_ms": total_ms, |
| 53 | +})) |
0 commit comments