From 2a4d1604b90921c343a95d6dfa23876a69af7f7e Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Tue, 17 Nov 2026 18:26:38 +0000 Subject: [PATCH 1/7] Add API for reading CPU instruction count on linux / macOS --- MetaBench/Perf.lean | 119 +++++++++++++++++++++++++++++++++++++++++++ example/bench-run.sh | 2 +- lakefile.lean | 33 ++++++++++++ lakefile.toml | 14 ----- native/perf_linux.c | 31 +++++++++++ native/perf_macos.c | 40 +++++++++++++++ 6 files changed, 224 insertions(+), 15 deletions(-) create mode 100644 MetaBench/Perf.lean create mode 100644 lakefile.lean delete mode 100644 lakefile.toml create mode 100644 native/perf_linux.c create mode 100644 native/perf_macos.c diff --git a/MetaBench/Perf.lean b/MetaBench/Perf.lean new file mode 100644 index 0000000..89088ce --- /dev/null +++ b/MetaBench/Perf.lean @@ -0,0 +1,119 @@ +module + +/-! +# CPU Instruction counting + +A `Perf.InstrCounter` counts the CPU instructions on a thread. + +* On Linux it is a hardware counter from `perf_event_open`. It records only user-space CPU instructions. +* On macOS it is the kernel's count for the current thread using `thread_selfcounts`. The count includes the + instructions the kernel runs on the thread's behalf. + +Native implementations are in `native/perf_linux.c` and `native/perf_macos.c`. +-/ + +namespace MetaBench.Perf + +/-- Open a counter for the calling thread. Returns its descriptor, or `-errno`. -/ +@[extern "metabench_instr_count_open"] +opaque openRaw : BaseIO Int32 + +/-- The count of the counter with descriptor `fd`, or `-errno`. -/ +@[extern "metabench_instr_count_read"] +opaque readRaw (fd : Int32) : BaseIO Int64 + +/-- Close the counter with descriptor `fd`. Returns `0` or `-errno`. -/ +@[extern "metabench_instr_count_close"] +opaque closeRaw (fd : Int32) : BaseIO Int32 + +/-- macOS native errnos. -/ +inductive MacOSErrno where + | ENOTSUP + +def MacOSErrno.ofInt32? : Int32 → Option MacOSErrno + | 45 => some .ENOTSUP + | _ => none + +instance : ToString MacOSErrno where + toString + | .ENOTSUP => "ENOTSUP" + +/-- Linux native errnos. -/ +inductive LinuxErrno where + | EPERM | ENOENT | EIO | EACCES | ENODEV | ENOSYS | EOPNOTSUPP + +def LinuxErrno.ofInt32? : Int32 → Option LinuxErrno + | 1 => some .EPERM + | 2 => some .ENOENT + | 5 => some .EIO + | 13 => some .EACCES + | 19 => some .ENODEV + | 38 => some .ENOSYS + | 95 => some .EOPNOTSUPP + | _ => none + +instance : ToString LinuxErrno where + toString + | .EPERM => "EPERM" + | .ENOENT => "ENOENT" + | .EIO => "EIO" + | .EACCES => "EACCES" + | .ENODEV => "ENODEV" + | .ENOSYS => "ENOSYS" + | .EOPNOTSUPP => "EOPNOTSUPP" + +def MacOSErrno.explain : MacOSErrno → String + | .ENOTSUP => "this machine does not record an instruction count" + +def LinuxErrno.explain : LinuxErrno → String + | .EPERM | .EACCES => + "the kernel refused perf_event_open: it needs `kernel.perf_event_paranoid` at 2 or lower" + | .ENOENT | .ENODEV | .EOPNOTSUPP => "this machine exposes no hardware instruction counter" + | .ENOSYS => "the kernel has no perf_event_open" + | .EIO => "perf_event_open or the read of its counter failed" + +def describe {ε : Type} [ToString ε] (errno : Int32) (e? : Option ε) (explain : ε → String) + (unnamed : String) : String := + match e? with + | some e => s!"{explain e} ({e}, errno {errno})" + | none => s!"{unnamed} (errno {errno})" + +def explain (errno : Int32) : String := + if System.Platform.isOSX then + describe errno (MacOSErrno.ofInt32? errno) MacOSErrno.explain "thread_selfcounts failed" + else + describe errno (LinuxErrno.ofInt32? errno) LinuxErrno.explain + "perf_event_open or the read of its counter failed" + +/-- A counter of CPU instructions. -/ +public structure InstrCounter where + private mk :: + /-- The descriptor `perf_event_open` returned on Linux. Unused on macOS. -/ + fd : Int32 + +/-- Open an instruction counter for the calling thread. -/ +def InstrCounter.open : IO InstrCounter := do + unless System.Platform.isLinux || System.Platform.isOSX do + throw <| .userError "bench.instructions: instructions can only be counted on Linux and macOS" + let fd ← openRaw + if fd < 0 then + throw <| .userError s!"bench.instructions: {explain (-fd)}" + return { fd } + +def InstrCounter.close (instrCounter : InstrCounter) : IO Unit := + discard <| closeRaw instrCounter.fd + +/-- The instruction counter's running total. It must be read on the thread that opened the counter. -/ +public def InstrCounter.read (instrCounter : InstrCounter) : IO Nat := do + let count ← readRaw instrCounter.fd + if count < 0 then + throw <| .userError s!"bench.instructions: {explain (-count).toInt32}" + return count.toNatClampNeg + +/-- Run `act` with a CPU instruction counter opened for the calling thread, and close it when `act` is done. -/ +public def withInstrCounter {m : Type → Type} {α : Type} [Monad m] [MonadLiftT IO m] [MonadFinally m] + (act : InstrCounter → m α) : m α := do + let instrCounter ← InstrCounter.open + try act instrCounter finally instrCounter.close + +end MetaBench.Perf diff --git a/example/bench-run.sh b/example/bench-run.sh index 0142d90..5b681a6 100755 --- a/example/bench-run.sh +++ b/example/bench-run.sh @@ -9,7 +9,7 @@ mathlib="${1:?usage: METABENCH= bench-run.sh suite="${2:?usage: METABENCH= bench-run.sh [lean args]}" shift 2 -if [ ! -f "$bench/lakefile.toml" ]; then +if [ ! -f "$bench/lakefile.lean" ]; then echo "error: METABENCH=$bench is not the benchmark library checkout" >&2; exit 2 fi if [ ! -f "$mathlib/.lake/build/lib/lean/Mathlib.olean" ]; then diff --git a/lakefile.lean b/lakefile.lean new file mode 100644 index 0000000..c065fae --- /dev/null +++ b/lakefile.lean @@ -0,0 +1,33 @@ +import Lake +open Lake DSL System + +package metabench where + version := v!"0.1.0" + leanOptions := #[⟨`autoImplicit, false⟩, ⟨`pp.fieldNotation, false⟩] + +@[default_target] +lean_lib MetaBench + +@[default_target] +lean_lib Tests where + globs := #[.submodules `Tests] + +/-- The system's half of the instruction counter, `native/perf_linux.c` or `native/perf_macos.c`, +compiled with the system's C compiler. -/ +target perfNative pkg : FilePath := do + let src ← + if Platform.isOSX then pure "perf_macos.c" + else if Platform.isLinux then pure "perf_linux.c" + else error "instructions can only be counted on Linux and macOS" + let srcJob ← inputTextFile <| pkg.dir / "native" / src + buildO (pkg.buildDir / "native" / "perf.o") srcJob (traceArgs := #["-O2", "-fPIC"]) + +/-- The library that `lean --load-dynlib` loads for `bench.instructions`: `MetaBench.Perf` compiled +to native code and linked with `perfNative`. -/ +@[default_target] +target perfDynlib pkg : Dynlib := do + let some mod ← findModule? `MetaBench.Perf | error "the module MetaBench.Perf is missing" + let leanO ← mod.oExport.fetch + let nativeO ← perfNative.fetch + buildLeanSharedLib "metabench_perf" (pkg.sharedLibDir / nameToSharedLib "metabench_perf") + #[leanO, nativeO] #[] diff --git a/lakefile.toml b/lakefile.toml deleted file mode 100644 index ed99440..0000000 --- a/lakefile.toml +++ /dev/null @@ -1,14 +0,0 @@ -name = "metabench" -version = "0.1.0" -defaultTargets = ["MetaBench", "Tests"] - -[leanOptions] -autoImplicit = false -pp.fieldNotation = false - -[[lean_lib]] -name = "MetaBench" - -[[lean_lib]] -name = "Tests" -globs = ["Tests.+"] diff --git a/native/perf_linux.c b/native/perf_linux.c new file mode 100644 index 0000000..0821d6a --- /dev/null +++ b/native/perf_linux.c @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +// Initialize a new CPU instructions counter. Returns its file descriptor or `-errno`. +int32_t metabench_instr_count_open(void) { + struct perf_event_attr attr = { + .type = PERF_TYPE_HARDWARE, + .size = sizeof attr, + .config = PERF_COUNT_HW_INSTRUCTIONS, + .exclude_kernel = 1, + .exclude_hv = 1, + }; + int fd = (int)syscall(SYS_perf_event_open, &attr, 0, -1, -1, PERF_FLAG_FD_CLOEXEC); + return fd < 0 ? -errno : fd; +} + +// Returns the count of the counter with descriptor `fd`, or `-errno`. +int64_t metabench_instr_count_read(int32_t fd) { + uint64_t count; + ssize_t n = read(fd, &count, sizeof count); + if (n != (ssize_t)sizeof count) return -(int64_t)(n < 0 ? errno : EIO); + return (int64_t)count; +} + +// Close the counter with descriptor `fd`. Returns 0, or `-errno`. +int32_t metabench_instr_count_close(int32_t fd) { + return close(fd) == 0 ? 0 : -errno; +} diff --git a/native/perf_macos.c b/native/perf_macos.c new file mode 100644 index 0000000..adb8d36 --- /dev/null +++ b/native/perf_macos.c @@ -0,0 +1,40 @@ +#include +#include +#include + +// `thread_selfcounts` is not declared publicly in the macOS SDK: +// +// Its implementation is in: +// https://github.com/apple-oss-distributions/xnu/blob/xnu-12377.121.6/bsd/kern/sys_recount.c#L174-L192 +// +// In our case (kind = THSC_CPI = 1) `thread_selfcounts` uses `struct thsc_cpi`: +// https://github.com/apple-oss-distributions/xnu/blob/ac9718fb1af618d5ce8678d0dc6e8a58f252216f/bsd/kern/sys_recount.c#L113-L116 +// +// `struct thsc_cpi` is defined at: +// https://github.com/apple-oss-distributions/xnu/blob/ac9718fb1af618d5ce8678d0dc6e8a58f252216f/bsd/sys/resource_private.h#L76 +struct thsc_cpi { + uint64_t tcpi_instructions; + uint64_t tcpi_cycles; +}; +int thread_selfcounts(uint32_t kind, void *dst, size_t size); + +// For compatibility with the Linux API. +int32_t metabench_instr_count_open(void) { + return 0; +} + +// Return the number of CPU instructions since the current thread started or `-errno`. `fd` is unused. +int64_t metabench_instr_count_read(int32_t fd) { + (void)fd; + struct thsc_cpi counts = {0}; + if (thread_selfcounts(1, &counts, sizeof counts) != 0) return -(int64_t)errno; + // Report a 0 count as an error. + if (counts.tcpi_instructions == 0) return -(int64_t)ENOTSUP; + return (int64_t)counts.tcpi_instructions; +} + +// For compatibility with the Linux API. +int32_t metabench_instr_count_close(int32_t fd) { + (void)fd; + return 0; +} From f41b46fd2cec5c62beebe79febd70d9999310fbb Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Tue, 17 Nov 2026 22:28:48 +0000 Subject: [PATCH 2/7] Update the lean-toolchain to v4.36.0 --- lean-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lean-toolchain b/lean-toolchain index 2afd387..00f8483 100644 --- a/lean-toolchain +++ b/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:v4.36.0-rc1 +leanprover/lean4:v4.36.0 From a5e5d24c26c6651804bed5fe21ec0ab18ea345f1 Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Tue, 17 Nov 2026 22:33:15 +0000 Subject: [PATCH 3/7] Add support for bench.instructions flag to report CPU instruction count --- MetaBench/Command.lean | 38 ++++++++++++++++++++++++++----------- MetaBench/Core.lean | 39 +++++++++++++++++++++++++++++--------- example/Suites/Bignum.lean | 19 +++++++++++++++++++ example/bench-run.sh | 18 ++++++++++++++++-- lakefile.lean | 5 +---- 5 files changed, 93 insertions(+), 26 deletions(-) create mode 100644 example/Suites/Bignum.lean diff --git a/MetaBench/Command.lean b/MetaBench/Command.lean index c86663a..1b63865 100644 --- a/MetaBench/Command.lean +++ b/MetaBench/Command.lean @@ -36,6 +36,9 @@ term. When `bench.kernelUnfolds n` is set the report also lists the `n` most frequently unfolded declarations during kernel checking. + +When `bench.instructions` is set each phase also reports the CPU instructions used. This depends on +the native library for Metabench.Perf being loaded. -/ open Lean Elab Command Term Meta @@ -72,6 +75,12 @@ meta register_option bench.tag : String := { descr := "#benchmark: a tag recorded with the JSON output, e.g. a git revision" } +meta register_option bench.instructions : Bool := { + defValue := false + descr := "#benchmark: if set, count the number of CPU instructions per-benchmark.\ + The native shared library associted with MetaBench.Perf must be laoded with `--load-dynlib`." +} + /-- The start time of this process, so every benchmark of one run carries the same `run` stamp. -/ meta initialize runStamp : String ← return (Std.Time.DateTime.ofTimestamp (← Std.Time.Timestamp.now) .UTC).toISO8601String @@ -193,17 +202,19 @@ meta def Spec.label (spec : Spec) : String := else "example" /-- Sample all phases of a single theorem. Returns the `PhaseSamples` and the checked theorem. -/ -meta def samplePhases (spec : Spec) : TermElabM (PhaseSamples × TheoremVal) := +meta def samplePhases (spec : Spec) (instrCounter? : Option Perf.InstrCounter) : + TermElabM (PhaseSamples × TheoremVal) := Term.withoutErrToSorry <| Term.withDeclName spec.declName <| Term.withLevelNames spec.levelNames do - let s0 ← Sample.now + let now := Sample.now instrCounter? + let s0 ← now Term.elabBinders spec.binders fun fvars => do let goal ← elabGoal spec.goal - let s1 ← Sample.now + let s1 ← now let proof ← elabProof spec.proof goal let thm ← mkTheorem spec.declName fvars goal proof - let s2 ← Sample.now + let s2 ← now kernelCheck thm - let s3 ← Sample.now + let s3 ← now let phases := fun | .goal => s1.sub s0 | .proof => s2.sub s1 @@ -211,8 +222,9 @@ meta def samplePhases (spec : Spec) : TermElabM (PhaseSamples × TheoremVal) := return (phases, thm) /-- One iteration under the ambient `maxHeartbeats`. -/ -meta def runSample (spec : Spec) : TermElabM (PhaseSamples × TheoremVal) := - Core.withCurrHeartbeats (samplePhases spec) +meta def runSample (spec : Spec) (instrCounter? : Option Perf.InstrCounter) : + TermElabM (PhaseSamples × TheoremVal) := + Core.withCurrHeartbeats (samplePhases spec instrCounter?) structure BenchRun where thm : TheoremVal @@ -221,7 +233,8 @@ structure BenchRun where /-- The kernel's unfolds for the declarations the warmup added, e.g. `decide +kernel`'s lemmas. -/ auxUnfolds : Std.TreeMap String Nat compare -meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do +/-- Run the warmup and the iterations, counting instructions with `instrCounter?` when there is one. -/ +meta def runBenchmark (spec : Spec) (instrCounter? : Option Perf.InstrCounter) : TermElabM BenchRun := do let iters := bench.iters.get (← getOptions) awaitPendingKernelChecks @@ -230,7 +243,7 @@ meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do let messages := (← getThe Core.State).messages let info ← getInfoState let initEnv ← getEnv - let (warmup, thm) ← tryFinally (withOptions (diagnostics.set · true) (runSample spec)) + let (warmup, thm) ← tryFinally (withOptions (diagnostics.set · true) (runSample spec instrCounter?)) (modifyEnv (Kernel.enableDiag · (Kernel.isDiagnosticsEnabled initEnv))) let auxUnfolds := counterDiff (Kernel.getDiagnostics initEnv).unfoldCounter (Kernel.getDiagnostics (← getEnv)).unfoldCounter @@ -241,7 +254,7 @@ meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do for _ in [0:iters] do -- Each iteration starts as a fresh declaration would do, where the elaborator caches are empty -- and `initEnv` is without the auxiliary lemmas the warmup added. - let (ps, _) ← withoutModifyingState <| withEnv initEnv <| withFreshCache <| runSample spec + let (ps, _) ← withoutModifyingState <| withEnv initEnv <| withFreshCache <| runSample spec instrCounter? samples := samples.push ps return { thm, warmup, iters := samples, auxUnfolds } @@ -277,7 +290,10 @@ public meta def elabBenchmarkCmd : CommandElab := fun stx => do let label := (label?.map (·.getString)).getD spec.label withScope (fun s => { s with opts := Elab.async.set s.opts false }) do runTermElabM fun _ => do - let { thm, warmup, iters := iterations, auxUnfolds } ← runBenchmark spec + -- The counter is opened here, on the thread that runs the benchmark, and closed after it. + let run := runBenchmark spec + let { thm, warmup, iters := iterations, auxUnfolds } ← + if bench.instructions.get (← getOptions) then Perf.withInstrCounter (run ∘ some) else run none -- Before the declaration is added: the diagnostic check adds it to a kernel environment again. let kernelUnfolds := (← checkUnfolds thm).foldl (fun m n c => m.insert n (m.getD n 0 + c)) auxUnfolds if spec.addDecl? then diff --git a/MetaBench/Core.lean b/MetaBench/Core.lean index b7599a5..630ead1 100644 --- a/MetaBench/Core.lean +++ b/MetaBench/Core.lean @@ -2,6 +2,7 @@ module public import Std.Time.Duration public import Lean.Data.Json +public import MetaBench.Perf import Lean open Lean Elab Std.Time @@ -11,21 +12,35 @@ namespace MetaBench public section /-- A `Sample` is a pair of a monotonic clock value (in nanoseconds) and the heartbeat count at that -moment. -/ +moment, with the measuring thread's instruction count when instructions are counted. -/ structure Sample where nanos : Nat heartbeats : Nat - deriving ToJson, FromJson + /-- A count of CPU instructions if they are counted. -/ + instructions : Option Nat := none + deriving FromJson + +instance : ToJson Sample where + toJson s := Json.mkObj <| + [("nanos", toJson s.nanos), ("heartbeats", toJson s.heartbeats)] + ++ Json.opt "instructions" s.instructions -@[inline] def Sample.now : BaseIO Sample := do - return { nanos := ← IO.monoNanosNow, heartbeats := ← IO.getNumHeartbeats } +/-- The sample of this moment, with the count of `instrCounter?` when there is one. -/ +@[inline] def Sample.now (instrCounter? : Option Perf.InstrCounter) : IO Sample := do + return { nanos := ← IO.monoNanosNow + heartbeats := ← IO.getNumHeartbeats + instructions := ← instrCounter?.mapM (·.read) } /-- The interval from `earlier` to `later`. -/ def Sample.sub (later earlier : Sample) : Sample := - { nanos := later.nanos - earlier.nanos, heartbeats := later.heartbeats - earlier.heartbeats } + { nanos := later.nanos - earlier.nanos + heartbeats := later.heartbeats - earlier.heartbeats + instructions := (· - ·) <$> later.instructions <*> earlier.instructions } def Sample.add (s1 s2 : Sample) : Sample := - { nanos := s1.nanos + s2.nanos, heartbeats := s1.heartbeats + s2.heartbeats } + { nanos := s1.nanos + s2.nanos + heartbeats := s1.heartbeats + s2.heartbeats + instructions := (· + ·) <$> s1.instructions <*> s2.instructions } /-- Elapsed time as a `Duration`, for display. -/ def Sample.toDuration (s : Sample) : Duration := .ofNanoseconds (.ofNat s.nanos) @@ -50,7 +65,7 @@ theorem Phase.mem_all (p : Phase) : p ∈ Phase.all := abbrev PhaseSamples := Phase → Sample def PhaseSamples.total (ps : PhaseSamples) : Sample := - Phase.all.foldl (fun acc p => acc.add (ps p) ) ⟨0, 0⟩ + Phase.all.foldl (fun acc p => acc.add (ps p) ) { nanos := 0, heartbeats := 0, instructions := some 0 } /-- Format a float with `prec` digits after the decimal point. -/ public def fmtFloat (x : Float) (precision : Nat := 2) : String := @@ -75,8 +90,9 @@ def summarize (xs : Array Nat) : Summary := let sorted := xs.qsort (· < ·) { min := sorted[0]?.getD 0, median := sorted[sorted.size / 2]?.getD 0, max := sorted.back?.getD 0 } -def Summary.cells (s : Summary) (iterations : Nat) (scale : Float) : Array String := - let fmt (x : Nat) := fmtFloat (x.toFloat / scale) +def Summary.cells (s : Summary) (iterations : Nat) (scale : Float) (precision : Nat := 2) : + Array String := + let fmt (x : Nat) := fmtFloat (x.toFloat / scale) precision #[fmt s.median] ++ if iterations > 1 then #[fmt s.min ++ "…" ++ fmt s.max] else #[] instance : ToJson PhaseSamples where @@ -131,10 +147,15 @@ def renderReport (r : Report) : String := let proofNodes := r.proofNodes let n := iters.size let heading (unit : String) : Array String := #[unit] ++ if n > 1 then #["min…max"] else #[] + let instructions_counted := !iters.isEmpty && iters.all fun it => Phase.all.all fun p => (it p).instructions.isSome let header := #["phase"] ++ heading "kHB" ++ heading "ms" + ++ if instructions_counted then heading "Minstr" else #[] let row (name : String) (samples : Array Sample) : Array String := #[name] ++ (summarize (samples.map (·.heartbeats))).cells n 1000.0 ++ (summarize (samples.map (·.nanos))).cells n 1_000_000 + ++ if instructions_counted then + (summarize (samples.map (·.instructions.getD 0))).cells n 1_000_000 (precision := 3) + else #[] let rows := #[header] ++ Phase.all.map (fun p => row p.name (iters.map (· p))) |>.push (row "total" (iters.map (·.total))) let kernelNs := (summarize (iters.map fun it => (it .kernel).nanos)).median diff --git a/example/Suites/Bignum.lean b/example/Suites/Bignum.lean new file mode 100644 index 0000000..a5682bf --- /dev/null +++ b/example/Suites/Bignum.lean @@ -0,0 +1,19 @@ +/- +Run in the root of the repo with: + + METABENCH=. example/bench-run.sh example/Suites/Bignum.lean -Dbench.instructions=true +-/ +import MetaBench + +-- `decide` only evaluates `3 ^ n` for exponents up to this threshold, which is 256 by default. +set_option exponentiation.threshold 1000000 + +#benchmark "pow-mod/1000" in example : 3 ^ 1000 % 1000003 = 73216 := by decide +#benchmark "pow-mod/10000" in example : 3 ^ 10000 % 1000003 = 218751 := by decide +#benchmark "pow-mod/100000" in example : 3 ^ 100000 % 1000003 = 799099 := by decide +#benchmark "pow-mod/1000000" in example : 3 ^ 1000000 % 1000003 = 222223 := by decide + +#benchmark "gcd/1000" in example : Nat.gcd (3 ^ 1000) (5 ^ 1000) = 1 := by decide +#benchmark "gcd/10000" in example : Nat.gcd (3 ^ 10000) (5 ^ 10000) = 1 := by decide +#benchmark "gcd/100000" in example : Nat.gcd (3 ^ 100000) (5 ^ 100000) = 1 := by decide +#benchmark "gcd/1000000" in example : Nat.gcd (3 ^ 1000000) (5 ^ 1000000) = 1 := by decide diff --git a/example/bench-run.sh b/example/bench-run.sh index 5b681a6..6b98c43 100755 --- a/example/bench-run.sh +++ b/example/bench-run.sh @@ -19,7 +19,21 @@ if ! diff -q "$bench/lean-toolchain" "$mathlib/lean-toolchain" >/dev/null; then echo "error: toolchain mismatch: harness $(cat "$bench/lean-toolchain"), checkout $(cat "$mathlib/lean-toolchain")" >&2 exit 2 fi -(cd "$bench" && lake build MetaBench >/dev/null) + +# Build the perfDynlib target, which provides the CPU instruction counter C API, +# only if a working system C compiler is available. +# +# If the -Dbench.instructions=true flag is passed and perfDynlib cannot be built +# then the first benchmark will fail. +load= +if cc -fsyntax-only -x c /dev/null >/dev/null 2>&1; then + (cd "$bench" && lake build -q MetaBench perfDynlib) + load="--load-dynlib=$(cd "$bench" && lake query -q perfDynlib)" +else + echo "warning: no working C compiler (cc), so the instruction counter is not built and" \ + "bench.instructions will fail" >&2 + (cd "$bench" && lake build -q MetaBench) +fi exec lake +"$(cat "$mathlib/lean-toolchain")" --dir "$mathlib" env \ sh -c 'LEAN_PATH="$LEAN_PATH:$0" exec lean -DElab.async=false "$@"' \ - "$bench/.lake/build/lib/lean" "$suite" "$@" + "$bench/.lake/build/lib/lean" ${load:+"$load"} "$suite" "$@" diff --git a/lakefile.lean b/lakefile.lean index c065fae..dc86a36 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -12,8 +12,7 @@ lean_lib MetaBench lean_lib Tests where globs := #[.submodules `Tests] -/-- The system's half of the instruction counter, `native/perf_linux.c` or `native/perf_macos.c`, -compiled with the system's C compiler. -/ +/-- Build the native code for the CPU instruction count feature -/ target perfNative pkg : FilePath := do let src ← if Platform.isOSX then pure "perf_macos.c" @@ -22,8 +21,6 @@ target perfNative pkg : FilePath := do let srcJob ← inputTextFile <| pkg.dir / "native" / src buildO (pkg.buildDir / "native" / "perf.o") srcJob (traceArgs := #["-O2", "-fPIC"]) -/-- The library that `lean --load-dynlib` loads for `bench.instructions`: `MetaBench.Perf` compiled -to native code and linked with `perfNative`. -/ @[default_target] target perfDynlib pkg : Dynlib := do let some mod ← findModule? `MetaBench.Perf | error "the module MetaBench.Perf is missing" From 6740b6adb5e5b9474a7b82e5e45ac33997b1b5d4 Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Tue, 17 Nov 2026 23:05:41 +0000 Subject: [PATCH 4/7] Add bench.instructions CI test --- .github/workflows/instructions.yml | 47 ++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 .github/workflows/instructions.yml diff --git a/.github/workflows/instructions.yml b/.github/workflows/instructions.yml new file mode 100644 index 0000000..be8dbc6 --- /dev/null +++ b/.github/workflows/instructions.yml @@ -0,0 +1,47 @@ +name: Instruction counting + +# Runs example/Suites/Bignum.lean with `bench.instructions` on Linux and macOS + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + bignum: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + + steps: + - uses: actions/checkout@v5 + + - name: Show the machine + run: | + if [ "$RUNNER_OS" = Linux ]; then + lscpu + else + sysctl -n machdep.cpu.brand_string + sw_vers + fi + + # Ubuntu's default `kernel.perf_event_paranoid` refuses perf_event_open to unprivileged users. + - name: Allow perf_event_open + if: runner.os == 'Linux' + run: sudo sysctl -w kernel.perf_event_paranoid=2 + + - uses: leanprover/lean-action@v1 + with: + auto-config: false + build: true + build-args: -q MetaBench perfDynlib + + # The suite imports nothing from Mathlib, so it runs in this package's environment rather than + # through example/bench-run.sh, which needs a built Mathlib checkout. + - name: Run the Bignum suite + run: | + lake env lean -DElab.async=false --load-dynlib="$(lake query -q perfDynlib)" \ + -Dbench.instructions=true example/Suites/Bignum.lean From 930bc70d16fe41d184e05d068f9553319a014717 Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Tue, 17 Nov 2026 23:14:43 +0000 Subject: [PATCH 5/7] Also add ubuntu-26.04-arm to the CPU instructions test --- .github/workflows/instructions.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/instructions.yml b/.github/workflows/instructions.yml index be8dbc6..8814909 100644 --- a/.github/workflows/instructions.yml +++ b/.github/workflows/instructions.yml @@ -12,7 +12,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest] + os: [ubuntu-latest, ubuntu-24.04-arm, ubuntu-26.04-arm, macos-latest] runs-on: ${{ matrix.os }} timeout-minutes: 20 From 4cb1913784851b4e86478f71431f4a354bccbb6c Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Wed, 18 Nov 2026 09:55:05 +0000 Subject: [PATCH 6/7] Run BigNum suite in tests with bench.instructions enabled for linux ARM --- .github/workflows/instructions.yml | 47 ---------------------------- .github/workflows/lean_action_ci.yml | 24 +++++++++++++- 2 files changed, 23 insertions(+), 48 deletions(-) delete mode 100644 .github/workflows/instructions.yml diff --git a/.github/workflows/instructions.yml b/.github/workflows/instructions.yml deleted file mode 100644 index 8814909..0000000 --- a/.github/workflows/instructions.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Instruction counting - -# Runs example/Suites/Bignum.lean with `bench.instructions` on Linux and macOS - -on: - push: - pull_request: - workflow_dispatch: - -jobs: - bignum: - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, ubuntu-24.04-arm, ubuntu-26.04-arm, macos-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 20 - - steps: - - uses: actions/checkout@v5 - - - name: Show the machine - run: | - if [ "$RUNNER_OS" = Linux ]; then - lscpu - else - sysctl -n machdep.cpu.brand_string - sw_vers - fi - - # Ubuntu's default `kernel.perf_event_paranoid` refuses perf_event_open to unprivileged users. - - name: Allow perf_event_open - if: runner.os == 'Linux' - run: sudo sysctl -w kernel.perf_event_paranoid=2 - - - uses: leanprover/lean-action@v1 - with: - auto-config: false - build: true - build-args: -q MetaBench perfDynlib - - # The suite imports nothing from Mathlib, so it runs in this package's environment rather than - # through example/bench-run.sh, which needs a built Mathlib checkout. - - name: Run the Bignum suite - run: | - lake env lean -DElab.async=false --load-dynlib="$(lake query -q perfDynlib)" \ - -Dbench.instructions=true example/Suites/Bignum.lean diff --git a/.github/workflows/lean_action_ci.yml b/.github/workflows/lean_action_ci.yml index c48bd68..1d675d1 100644 --- a/.github/workflows/lean_action_ci.yml +++ b/.github/workflows/lean_action_ci.yml @@ -7,8 +7,30 @@ on: jobs: build: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + instructions: false + - os: macos-latest + instructions: false + # Of GitHub's runners, only the Linux ARM ones expose a CPU instruction counter. + - os: ubuntu-26.04-arm + instructions: true + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v5 + + # Ubuntu's default `kernel.perf_event_paranoid` refuses perf_event_open to unprivileged users. + - name: Allow perf_event_open + if: matrix.instructions + run: sudo sysctl -w kernel.perf_event_paranoid=2 + - uses: leanprover/lean-action@v1 + + - name: Run the Bignum suite + run: | + lake env lean -DElab.async=false --load-dynlib="$(lake query -q perfDynlib)" \ + -Dbench.instructions=${{ matrix.instructions }} example/Suites/Bignum.lean From 6bd075b3c3ee6738c9d6dfee0b8002b81902f08c Mon Sep 17 00:00:00 2001 From: Paul Cadman Date: Wed, 18 Nov 2026 10:13:58 +0000 Subject: [PATCH 7/7] Update README with information about counting CPU instructions --- README.md | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 84aafde..3d5995f 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,31 @@ Each object has the fields: - `warmup`: the samples of the warmup, per phase. - `iters`: the samples of every measured iteration, per phase. -A sample is `{"heartbeats": n, "nanos": n}` and the phases are `goal`, `proof` and `kernel`. The -file loads into pandas with `pd.read_json(path, lines=True)`. On the Lean side the same record is -`MetaBench.Report`, with `ToJson` and `FromJson` instances. +A sample is `{"heartbeats": n, "nanos": n}` and the phases are `goal`, `proof` and `kernel`. When +[instructions are counted](#counting-instructions) a sample also contains the `"instructions"` field. + +## Counting CPU instructions + +Pass the `-Dbench.instructions=true` flag to count the CPU instructions run on each phase. Unlike +heartbeats the count sees arithmetic on large numbers, and it varies less than the clock. + +``` +METABENCH=. example/bench-run.sh example/Suites/Det.lean -Dbench.instructions=true +``` + +The report has a `Minstr` column in units of millions of CPU instructions. + +This feature is provided as a native library in the `perfDynlib` target that lake builds with the +system's C compiler. The path to the built shared library (which can be obtained using +`lake query -q perfDynlib`) must be passed to lean using its `--load-dynlib` flag whenever the +`-Dbench.instructions=true` flag is used. + +If a system C compiler is available then `example/bench-run.sh` automatically builds the `perfDynlib` target and passes `--load-dynlib`. + +The Linux and macOS implementations count instructions differently, so the numbers are not comparable with each other: + +- **Linux** ([`native/perf_linux.c`](native/perf_linux.c)) reads a hardware counter with + `perf_event_open`. Some CI and container hosts do not expose this counter and this feature will + not work in this case. `kernel.perf_event_paranoid` must be 2 or lower. +- **macOS** ([`native/perf_macos.c`](native/perf_macos.c)) reads the kernel's count for the thread + with `thread_selfcounts`.