Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 177 additions & 0 deletions .github/scripts/compare-search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Same-host before/after check; timing is evidence, not a noisy merge gate."""
import csv
import importlib.util
import json
import os
from pathlib import Path
import shutil
import statistics

ROOT = Path(__file__).resolve().parents[2]
WORK = ROOT / "build/search-performance"
BASELINE = "452314a7ca51f90a7a8fa66930947164af8fc4f6"
HARNESS = "ecf31d3d65a45466222dfb0f358e176a22d1bc1c"

def main():
harness = WORK / "harness"
spec = importlib.util.spec_from_file_location("baseline_bench", harness / "benchmarks/run.py")
bench = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bench)
assert bench.output(["git", "rev-parse", "HEAD"], WORK / "before") == BASELINE
assert bench.output(["git", "rev-parse", "HEAD"], harness) == HARNESS
deps = WORK / "deps"
for lib, sha in bench.PINS.items():
assert bench.output(["git", "rev-parse", "HEAD"], deps / lib) == sha
after = WORK / "after"
for folder in ("src", "include"):
shutil.copytree(ROOT / folder, after / folder, dirs_exist_ok=True)

# Extend the existing 28 cases with common endpoint bytes, misses
# across the private cutoff, and repetitive text with both bytes present.
source = (harness / "benchmarks/strings.c").read_text()
source = source.replace("RESERVED = 16", "RESERVED = 16, COMMON = 32, PERIODIC = 64, END_PRESENT = 128")
anchor = ' {"copy_cstr_16"'
extra = [
("common8_miss_65536", 8, "COMMON"),
("common8_end_65536", 8, "COMMON | HIT_END"),
("periodic8_miss_65536", 8, "PERIODIC"),
("common31_miss_65536", 31, "COMMON"),
("common32_miss_65536", 32, "COMMON"),
("common33_miss_65536", 33, "COMMON"),
("repeated128_end_present_miss_65536", 128, "REPEATED | END_PRESENT"),
("common257_miss_65536", 257, "COMMON"),
]
assert anchor in source
source = source.replace(anchor, "".join(
f' {{"{name}", FIND, 65536, {m}, {flags}}},\n'
for name, m, flags in extra) + anchor, 1)
anchor = " f->sep = "
assert anchor in source
setup = """
if (c->op == FIND) {
if (c->flags & COMMON)
for (size_t i = 0; i < m; ++i) f->needle[i] = (char)('a' + i % 25);
if (c->flags & PERIODIC) {
for (size_t i = 0; i < c->n; ++i) f->data[i] = i % 2 ? 'b' : 'a';
memset(f->needle, 'a', m);
f->needle[m - 1] = 'b';
}
if (c->flags & END_PRESENT)
for (size_t i = m - 2; i < c->n; i += m - 1) f->data[i] = 'b';
if (c->flags & HIT_FRONT) memcpy(f->data, f->needle, m);
if (c->flags & HIT_END) memcpy(f->data + c->n - m, f->needle, m);
}
"""
source = source.replace(anchor, setup + anchor, 1)
anchor = " Fixture f; prepare(&f, &cases[ci]);"
assert anchor in source
source = source.replace(anchor,
" if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;"
+ chr(10) + anchor, 1)
search_cases = sum(1 for line in source.splitlines()
if line.lstrip().startswith('{"')
and (", FIND," in line or ", FIND_CHAR," in line))
timing_names = [
"find8_miss_65536", "find128_repeated_miss_65536",
"find_char_end_65536",
"common8_miss_65536", "common33_miss_65536",
"periodic8_miss_65536", "repeated128_end_present_miss_65536",
]
selected = " || ".join(f'strcmp(cases[ci].name, "{name}") == 0'
for name in timing_names)
source = source.replace(anchor,
f" if (!check_only && !({selected})) continue;"
+ chr(10) + anchor, 1)
repeats = 3
for variant in ("before", "after"):
folder = WORK / variant / "benchmarks"
folder.mkdir(parents=True, exist_ok=True)
(folder / "strings.c").write_text(source)

cpu = min(os.sched_getaffinity(0))
out = WORK / "results"
out.mkdir(parents=True, exist_ok=True)
metadata = {
"before": BASELINE, "after": bench.output(["git", "rev-parse", "HEAD"], ROOT),
"harness": HARNESS, "dependencies": bench.PINS,
"pinned_cpu": cpu, "lscpu": json.loads(bench.output(["lscpu", "-J"])),
"libc": bench.output(["ldd", "--version"]).splitlines()[0],
"timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"],
"portable_flags": ["-DSX_FORCE_NO_MEMMEM"],
"correctness_cases": search_cases, "timing_cases": len(timing_names),
"processes": repeats, "samples_per_process": 11, "samples": 11 * repeats, "target_sample_ns": 20000000,
"note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.",
}
(out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n")
(out / "strings.c").write_text(source)
print("SEARCH_COMPARE_ENV=" + json.dumps(metadata), flush=True)
report = ["# Search before/after", "",
"Same job, pinned CPU, -O3, no LTO; 3 fresh processes, 11 hot-input samples each.",
"Sequential runs are subject to host scheduling/frequency changes; small differences are inconclusive.", ""]
env = os.environ.copy()
env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1",
UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")
common_flags = list(bench.COMMON)
for ci, cc in enumerate(("gcc-14", "clang-19")):
results = {}
for variant in (("before", "after", "portable") if ci == 0 else ("portable", "after", "before")):
bench.ROOT = WORK / ("before" if variant == "before" else "after")
bench.COMMON = common_flags + (["-DSX_FORCE_NO_MEMMEM"] if variant == "portable" else [])
folder = out / cc / variant
folder.mkdir(parents=True, exist_ok=True)
log = folder / "commands.log"
check = bench.compile_binary(cc, folder / "check", "check", deps, log)
bench.invoke([str(check), "--check"], log, env=env, cpu=cpu)
binary = bench.compile_binary(cc, folder / "timing", "timing", deps, log)
rows = []
for process in range(repeats):
samples = folder / f"samples-{process}.csv"
bench.invoke([str(binary)], log, stdout=samples, cpu=cpu)
rows.extend(csv.DictReader(samples.open()))
alloc = bench.compile_binary(cc, folder / "alloc", "alloc", deps, log)
bench.invoke([str(alloc)], log, stdout=folder / "allocations.csv", cpu=cpu)
memory = {(r["case"], r["library"]): r
for r in csv.DictReader((folder / "allocations.csv").open())}
groups = {}
for r in rows:
groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"]))
assert len(groups) == len(timing_names) * 3, len(groups)
stats = {}
for (case, library), values in groups.items():
assert len(values) == 11 * repeats
stats[case, library] = {
"case": case, "library": library,
"median_ns": statistics.median(values),
"p10_ns": bench.quantile(values, .1), "p90_ns": bench.quantile(values, .9),
"malloc_calls": int(memory[case, library]["malloc_calls"]),
}
(folder / "summary.json").write_text(json.dumps(list(stats.values()), indent=2) + "\n")
results[variant] = stats
bench.COMMON = common_flags
report += [f"## {bench.output([cc, '--version']).splitlines()[0]}", "",
"| Case | Before ns | Native ns | Portable ns | Native speedup | Portable speedup |",
"| --- | ---: | ---: | ---: | ---: | ---: |"]
compared = []
for key, before in sorted(results["before"].items()):
case, library = key
if not library.startswith("StringX"):
continue
after_row = results["after"][key]
ratio = before["median_ns"] / after_row["median_ns"]
portable = results["portable"][key]
portable_ratio = before["median_ns"] / portable["median_ns"]
row = {"case": case, "before": before, "after": after_row, "speedup": ratio,
"portable": portable, "portable_speedup": portable_ratio}
compared.append(row)
report.append(f"| {case} | {before['median_ns']:.2f} | {after_row['median_ns']:.2f} | {portable['median_ns']:.2f} | {ratio:.2f}x | {portable_ratio:.2f}x |")
print("SEARCH_COMPARE_JSON=" + json.dumps({"compiler": cc, "results": compared}), flush=True)
report.append("")
text = "\n".join(report) + "\n"
(out / "summary.md").write_text(text)
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as dest:
dest.write(text)

if __name__ == "__main__":
main()
78 changes: 78 additions & 0 deletions .github/workflows/search-performance.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
name: Search performance

on:
pull_request:
paths:
- 'src/sx_core.c'
- '.github/scripts/compare-search.py'
- '.github/workflows/search-performance.yml'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: search-performance-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

defaults:
run:
shell: bash

jobs:
benchmark:
name: Search before and after (GCC and Clang)
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
persist-credentials: false
- name: Install benchmark compilers and PCRE2 headers
timeout-minutes: 5
run: |
if test -f /etc/apt/apt-mirrors.txt; then
printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null
fi
sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update
sudo env DEBIAN_FRONTEND=noninteractive apt-get \
-o DPkg::Lock::Timeout=120 -o Acquire::Retries=3 \
-o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \
install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev libpcre2-dev pkg-config
- name: Check out the library baseline
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: 452314a7ca51f90a7a8fa66930947164af8fc4f6
path: build/search-performance/before
persist-credentials: false
- name: Check out the immutable benchmark harness
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ecf31d3d65a45466222dfb0f358e176a22d1bc1c
path: build/search-performance/harness
persist-credentials: false
- name: Check out pinned SDS
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: antirez/sds
ref: 5347739b1581fcba74fd5cab1fc21d2aef317d71
path: build/search-performance/deps/sds
persist-credentials: false
- name: Check out pinned bstrlib
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: websnarf/bstrlib
ref: f0ff1e808102a42cdc7204a4bb6fe231a24c4546
path: build/search-performance/deps/bstrlib
persist-credentials: false
- name: Validate, measure and report on one pinned CPU
run: python3 .github/scripts/compare-search.py
- name: Preserve raw samples and environment
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: search-performance-${{ github.run_id }}
path: build/search-performance/results
if-no-files-found: ignore
retention-days: 14
78 changes: 73 additions & 5 deletions src/sx_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ extern void *memrchr(const void *s, int c, size_t n);
*
* opt bit1 (2): "first" -- single result: leftmost (or, with right,
* rightmost) match position, or (find_ret_t)-1 if none.
* No allocation.
* KMP fallback may allocate a temporary prefix table.
* opt bit1 clear: ALL mode -- malloc'd size_t array, caller frees:
* arr[0] = count, arr[1..count] = positions in ascending order
* (overlapping matches included). count == 0 -> a valid {0} array.
Expand Down Expand Up @@ -477,6 +477,74 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len,
r[0] = cnt;
return (find_ret_t)r;
}
/* Keep optional native checks out of the portable KMP callers'
optimizer context. The forced build uses the original path directly. */
#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__)
extern void *memmem(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen);

/* GCC and Clang support this private hint on glibc targets. It keeps
native-path conditions from changing the fallback's specialization. */
static __attribute__((noinline)) int
try_native_find_first(const sx_t *h, const char *needle, int len,
size_t boundary, find_ret_t *result) {
const size_t H = h->ref->len;
const size_t m = (size_t)len;
const char *t = h->ref->ptr;
size_t l = boundary;
*result = (find_ret_t)-1;
if (len <= 0 || l >= H || m > H - l)
return 1;
if (m == 1) {
const char *p = memchr(t + l, needle[0], H - l);
if (p)
*result = (find_ret_t)(p - t);
return 1;
}

/* Front hits need no preprocessing or prefix-table allocation. */
if (memcmp(t + l, needle, m) == 0) {
*result = (find_ret_t)l;
return 1;
}
if (H - l == m)
return 1;

/* Only [l+1, H-m] can start another legal window. */
const char *p = memchr(t + l + 1, needle[0], H - m - l);
if (!p)
return 1;
l = (size_t)(p - t);

/* A valid window must also end with the needle's final byte.
No earlier start can match before this first possible endpoint. */
p = memchr(t + l + m - 1, needle[m - 1], H - l - m + 1);
if (!p)
return 1;
l = (size_t)(p - t) - (m - 1);

/* Limit native search to short patterns. Long repeated prefixes can
be a bad case for libc's short-pattern implementation. */
if (m <= 32) {
p = memmem(t + l, H - l, needle, m);
if (p)
*result = (find_ret_t)(p - t);
return 1;
}
return 0; /* original KMP handles the unresolved long needle */
}
#endif

static inline find_ret_t find_first(const sx_t *h, const char *needle, int len,
size_t boundary) {
#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__)
find_ret_t result;
if (try_native_find_first(h, needle, len, boundary, &result))
return result;
#endif
return find(h, needle, len, boundary, 2);
}

/* Wrappers translate the public API onto find(). Per the buffer model,
a needle's searchable length is its CONTENT length (the trailing '\0'
at ptr[len] is not content): sx_find* pass the needle's own length,
Expand All @@ -485,7 +553,7 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len,
SYMBOL_PUBLIC size_t sx_find(const sx_t *h, const sx_t *needle) {
if (!h || !needle)
return (size_t)-1;
return (size_t)find(h, needle->ref->ptr, needle->ref->len, 0, 2);
return (size_t)find_first(h, needle->ref->ptr, needle->ref->len, 0);
}
SYMBOL_PUBLIC size_t sx_find_view(const sx_t *h, sx_view_t needle) {
return sx_find_view_b(h, needle, 0);
Expand All @@ -495,13 +563,13 @@ SYMBOL_PUBLIC size_t sx_find_view_b(const sx_t *h, sx_view_t needle,
size_t boundary) {
if (!h)
return (size_t)-1;
return (size_t)find(h, needle.ref->ptr + needle.offset, needle.len, boundary,
2);
return (size_t)find_first(h, needle.ref->ptr + needle.offset, needle.len,
boundary);
}
SYMBOL_PUBLIC size_t sx_find_cstr(const sx_t *h, const char *needle) {
if (!h || !needle)
return (size_t)-1;
return (size_t)find(h, needle, (int)strlen(needle), 0, 2);
return (size_t)find_first(h, needle, (int)strlen(needle), 0);
}
SYMBOL_PUBLIC size_t sx_find_char(const sx_t *h, char c) {
if (!h)
Expand Down
13 changes: 13 additions & 0 deletions tests/find_differential.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Include include
// Include src
// Include /usr/lib/forge/include
// Source src/sx_raw.c
// Source src/sx_core.c
// Source src/sx_adv.c
// Option -std=c23
// Option -O1
// Option -g
// Option -fsanitize=address,undefined
// Option -fno-omit-frame-pointer
// Library /usr/local/lib
#include "find_differential.h"
Loading
Loading