diff --git a/benchmark/src/androidTest/java/com/vitorpamplona/quartz/benchmark/Secp256k1Benchmark.kt b/benchmark/src/androidTest/java/com/vitorpamplona/quartz/benchmark/Secp256k1Benchmark.kt index 283435916..c23267118 100644 --- a/benchmark/src/androidTest/java/com/vitorpamplona/quartz/benchmark/Secp256k1Benchmark.kt +++ b/benchmark/src/androidTest/java/com/vitorpamplona/quartz/benchmark/Secp256k1Benchmark.kt @@ -36,8 +36,19 @@ import org.junit.runner.RunWith * Android microbenchmark for all secp256k1 operations used by Nostr. * * Uses AndroidX Benchmark (Jetpack Microbenchmark) for accurate, warmed-up - * measurements on real Android hardware/emulator. Results appear in Android - * Studio's benchmark output with ns/op, allocations, and percentiles. + * measurements on real Android hardware. Results appear in Android Studio's + * benchmark output with ns/op, allocations, and percentiles. + * + * Tests are structured as matched pairs: "Foo" uses the native C library (ACINQ/JNI), + * "FooOurs" uses the pure-Kotlin implementation. This allows direct comparison of + * each operation between native and Kotlin on the same device. + * + * NOTE: verifySchnorr uses the same pubkey repeatedly, so it benefits from the + * pubkey decompression cache and P-table cache. This is realistic for Nostr + * (feed from one author) but not representative of first-time verification. + * + * Test data is the same across all 3 platform benchmarks (JVM, Android, K/Native) + * for cross-platform comparability. * * Run with: ./gradlew :benchmark:connectedAndroidTest */ @@ -45,7 +56,7 @@ import org.junit.runner.RunWith class Secp256k1Benchmark { @get:Rule val benchmarkRule = BenchmarkRule() - // Test data + // Test data (same across all 3 platform benchmarks for comparability) private val privKey = "67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530".hexToByteArray() private val msg32 = "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89".hexToByteArray() private val auxRand = "0000000000000000000000000000000000000000000000000000000000000001".hexToByteArray() @@ -54,19 +65,12 @@ class Secp256k1Benchmark { private val compressedPubKey = Secp256k1Instance.compressedPubKeyFor(privKey) private val xOnlyPub = compressedPubKey.copyOfRange(1, 33) private val signature = Secp256k1Instance.signSchnorr(msg32, privKey, auxRand) - private val uncompressedPubKey by lazy { - val seckey2 = "3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".hexToByteArray() - val compressed = Secp256k1Instance.compressedPubKeyFor(seckey2) - // We need an uncompressed key for pubKeyCompress benchmark - // Use the x-coordinate and compute full key - compressed // will be compressed for the benchmark - } // ECDH test data private val privKey2 = "3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3".hexToByteArray() private val pubKey2XOnly = Secp256k1Instance.compressedPubKeyFor(privKey2).copyOfRange(1, 33) - // ==================== Core Nostr operations ==================== + // ==================== Core Nostr operations (Native C via ACINQ/JNI) ==================== @Test fun verifySchnorr() { @@ -89,8 +93,6 @@ class Secp256k1Benchmark { } } - // ==================== Key operations ==================== - @Test fun secKeyVerify() { benchmarkRule.measureRepeated { @@ -98,14 +100,6 @@ class Secp256k1Benchmark { } } - @Test - fun pubKeyCompress() { - // Compress an already-compressed key (fast path) - benchmarkRule.measureRepeated { - assertNotNull(Secp256k1Instance.compressedPubKeyFor(privKey)) - } - } - @Test fun privateKeyAdd() { benchmarkRule.measureRepeated { @@ -113,8 +107,6 @@ class Secp256k1Benchmark { } } - // ==================== ECDH (NIP-04, NIP-44) ==================== - @Test fun pubKeyTweakMulCompact() { benchmarkRule.measureRepeated { @@ -122,6 +114,8 @@ class Secp256k1Benchmark { } } + // ==================== Core Nostr operations (Pure Kotlin) ==================== + @Test fun verifySchnorrOurs() { benchmarkRule.measureRepeated { @@ -143,8 +137,6 @@ class Secp256k1Benchmark { } } - // ==================== Key operations ==================== - @Test fun secKeyVerifyOurs() { benchmarkRule.measureRepeated { @@ -152,14 +144,6 @@ class Secp256k1Benchmark { } } - @Test - fun pubKeyCompressOurs() { - // Compress an already-compressed key (fast path) - benchmarkRule.measureRepeated { - assertNotNull(Secp256k1InstanceOurs.compressedPubKeyFor(privKey)) - } - } - @Test fun privateKeyAddOurs() { benchmarkRule.measureRepeated { @@ -167,8 +151,6 @@ class Secp256k1Benchmark { } } - // ==================== ECDH (NIP-04, NIP-44) ==================== - @Test fun pubKeyTweakMulCompactOurs() { benchmarkRule.measureRepeated { diff --git a/quartz/src/jvmTest/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1Benchmark.kt b/quartz/src/jvmTest/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1Benchmark.kt index 0902c8a25..3a8a3c1a7 100644 --- a/quartz/src/jvmTest/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1Benchmark.kt +++ b/quartz/src/jvmTest/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1Benchmark.kt @@ -26,13 +26,19 @@ import fr.acinq.secp256k1.Secp256k1 as NativeSecp256k1 /** * Benchmark comparing the pure-Kotlin secp256k1 implementation against - * the native ACINQ/secp256k1-kmp JNI bindings. + * the native ACINQ/secp256k1-kmp JNI bindings on JVM (HotSpot C2). * - * Each benchmark runs warmup iterations, then measures the timed iterations. - * Results are printed as ops/sec and relative speed. + * Each benchmark runs warmup iterations to trigger JIT compilation, then + * measures timed iterations. Results are printed as ops/sec and relative speed. + * + * NOTE: verifySchnorr and signSchnorr use the same pubkey repeatedly, so they + * benefit from the pubkey decompression cache and P-table cache. This is realistic + * for Nostr (feed from one author) but not representative of first-time verification. + * + * Run with: ./gradlew :quartz:jvmTest --tests "*.Secp256k1Benchmark" */ class Secp256k1Benchmark { - // Test data + // Test data (same across all 3 platform benchmarks for comparability) private val privKey = hexToBytes("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530") private val msg32 = hexToBytes("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89") private val auxRand = hexToBytes("0000000000000000000000000000000000000000000000000000000000000001") @@ -55,11 +61,7 @@ class Secp256k1Benchmark { // ECDH test data private val privKey2 = hexToBytes("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3") - private val pubKey2Uncompressed = - hexToBytes( - "040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE5" + - "95DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40", - ) + private val pub2xOnly = hexToBytes("c2f9d9948dc8c7c38321e4b85c8558872eafa0641cd269db76848a6073e69133") private val h02 = byteArrayOf(0x02) // ============================================================ @@ -78,7 +80,7 @@ class Secp256k1Benchmark { override fun toString(): String = String.format( - "%-25s Native: %,8d ops/s Kotlin: %,8d ops/s Ratio: %.1fx slower", + "%-25s Native: %,8d ops/s Kotlin: %,8d ops/s Ratio: %.1fx", name, nativeOpsPerSec, kotlinOpsPerSec, @@ -130,7 +132,7 @@ class Secp256k1Benchmark { val results = mutableListOf() - // --- verifySchnorr --- + // --- verifySchnorr (same pubkey = cache-warm, typical Nostr pattern) --- results += bench( name = "verifySchnorr", @@ -146,7 +148,7 @@ class Secp256k1Benchmark { }, ) - // --- signSchnorr (derives pubkey from seckey each time) --- + // --- signSchnorr (derives pubkey from seckey each time — both sides do the same work) --- results += bench( name = "signSchnorr", @@ -162,7 +164,11 @@ class Secp256k1Benchmark { }, ) - // --- signSchnorrWithPubKey (pre-computed pubkey, no self-verify — matches C) --- + // --- signSchnorr (cached pk) --- + // NOTE: The C library's signSchnorr always derives the pubkey internally. + // Our signSchnorrWithPubKey skips that derivation. This is NOT an apples-to-apples + // comparison — it shows what's possible when the caller caches the compressed pubkey. + // The native baseline here is the same signSchnorr (with pubkey derivation). results += bench( name = "signSchnorr (cached pk)", @@ -209,32 +215,17 @@ class Secp256k1Benchmark { }, ) - // --- pubKeyTweakMul (ECDH) --- + // --- compressedPubKeyFor (create + compress combined) --- results += bench( - name = "pubKeyTweakMul (ECDH)", + name = "compressedPubKeyFor", warmup = 1000, - iterations = 3000, - nativeOp = { native.pubKeyTweakMul(pubKey2Uncompressed.copyOf(), privKey) }, + iterations = 5000, + nativeOp = { native.pubKeyCompress(native.pubkeyCreate(privKey)) }, kotlinOp = { - com.vitorpamplona.quartz.utils.secp256k1.Secp256k1.pubKeyTweakMul( - pubKey2Uncompressed, - privKey, - ) - }, - ) - - // --- privKeyTweakAdd --- - results += - bench( - name = "privKeyTweakAdd", - warmup = 1000, - iterations = 50000, - nativeOp = { native.privKeyTweakAdd(privKey.copyOf(), privKey2) }, - kotlinOp = { - com.vitorpamplona.quartz.utils.secp256k1.Secp256k1.privKeyTweakAdd( - privKey, - privKey2, + com.vitorpamplona.quartz.utils.secp256k1.Secp256k1.pubKeyCompress( + com.vitorpamplona.quartz.utils.secp256k1.Secp256k1 + .pubkeyCreate(privKey), ) }, ) @@ -252,39 +243,25 @@ class Secp256k1Benchmark { }, ) - // --- compressedPubKeyFor (create + compress combined) --- + // --- privKeyTweakAdd --- + // NOTE: The ACINQ wrapper mutates its first argument, requiring .copyOf() on + // the native side. This adds one allocation to the native measurement. results += bench( - name = "compressedPubKeyFor", + name = "privKeyTweakAdd", warmup = 1000, - iterations = 5000, - nativeOp = { native.pubKeyCompress(native.pubkeyCreate(privKey)) }, + iterations = 50000, + nativeOp = { native.privKeyTweakAdd(privKey.copyOf(), privKey2) }, kotlinOp = { - com.vitorpamplona.quartz.utils.secp256k1.Secp256k1.pubKeyCompress( - com.vitorpamplona.quartz.utils.secp256k1.Secp256k1 - .pubkeyCreate(privKey), + com.vitorpamplona.quartz.utils.secp256k1.Secp256k1.privKeyTweakAdd( + privKey, + privKey2, ) }, ) - // --- pubKeyTweakMulCompact (old pattern via pubKeyTweakMul) --- - val pub2xOnly = hexToBytes("c2f9d9948dc8c7c38321e4b85c8558872eafa0641cd269db76848a6073e69133") - results += - bench( - name = "tweakMulCompact (old)", - warmup = 1000, - iterations = 3000, - nativeOp = { native.pubKeyTweakMul(h02 + pub2xOnly, privKey).copyOfRange(1, 33) }, - kotlinOp = { - com.vitorpamplona.quartz.utils.secp256k1.Secp256k1 - .pubKeyTweakMul( - h02 + pub2xOnly, - privKey, - ).copyOfRange(1, 33) - }, - ) - - // --- ecdhXOnly (actual Nostr ECDH path) --- + // --- ecdhXOnly (Nostr NIP-04/NIP-44 ECDH path) --- + // Native has no ecdhXOnly — compare against pubKeyTweakMul + extract x. results += bench( name = "ecdhXOnly (Nostr)", @@ -300,7 +277,7 @@ class Secp256k1Benchmark { // Print results println() println("=".repeat(90)) - println("secp256k1 Benchmark: Native (ACINQ/JNI) vs Pure Kotlin") + println("secp256k1 Benchmark: Native (ACINQ/JNI) vs Pure Kotlin on JVM (HotSpot C2)") println("=".repeat(90)) for (r in results) { println(r) @@ -308,7 +285,9 @@ class Secp256k1Benchmark { println("=".repeat(90)) // ==================== Batch verification benchmark ==================== - // Same pubkey, n events — the typical Nostr pattern (feed from one author) + // Same pubkey, n events — the typical Nostr pattern (feed from one author). + // Batch verify uses scalar+point summation: one mulDoubleG for the whole batch + // instead of n individual mulDoubleG calls. val batchPub = kotlinXOnlyPub for (batchSize in intArrayOf(4, 8, 16, 32)) { val sigs = mutableListOf() diff --git a/quartz/src/linuxX64Test/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1NativeBenchmark.kt b/quartz/src/linuxX64Test/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1NativeBenchmark.kt index 50bbabdc3..442ea0d57 100644 --- a/quartz/src/linuxX64Test/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1NativeBenchmark.kt +++ b/quartz/src/linuxX64Test/kotlin/com/vitorpamplona/quartz/utils/secp256k1/Secp256k1NativeBenchmark.kt @@ -25,23 +25,30 @@ import kotlin.test.assertTrue import kotlin.time.TimeSource /** - * Benchmark for the pure-Kotlin secp256k1 implementation on Kotlin/Native (LLVM backend). + * Benchmark for the pure-Kotlin secp256k1 implementation on Kotlin/Native (LLVM AOT). * - * Measures the same operations as the JVM benchmark (Secp256k1Benchmark.kt) so results - * can be directly compared across runtimes: + * Measures the same operations as the JVM benchmark (Secp256k1Benchmark.kt) and the + * Android benchmark (benchmark module) so results can be compared across runtimes: * - Kotlin/Native LLVM AOT (this benchmark) * - JVM HotSpot C2 JIT (jvmTest/Secp256k1Benchmark.kt) * - Android ART JIT (benchmark module) - * - Native C libsecp256k1 (JVM benchmark's native baseline) + * + * No native C comparison is available (JNI doesn't exist on K/N). + * Compare against the JVM benchmark's native column for the C baseline. + * + * NOTE: verifySchnorr uses the same pubkey repeatedly, so it benefits from the + * pubkey decompression cache and P-table cache. This is realistic for Nostr + * (feed from one author) but not representative of first-time verification. + * + * Test data is the same across all 3 platform benchmarks for cross-platform comparability. * * Run with: ./gradlew :quartz:linuxX64Test --tests "*.Secp256k1NativeBenchmark" * - * To inspect the LLVM IR or assembly generated for hot functions: - * ./gradlew :quartz:linkDebugTestLinuxX64 (or linkReleaseTestLinuxX64) - * objdump -d build/bin/linuxX64/debugTest/test.kexe | grep -A 50 "fieldMulApi" + * IMPORTANT: Requires -opt in the compiler options for meaningful results. + * Without it, K/N compiles in debug mode (~12x slower). See build.gradle.kts. */ class Secp256k1NativeBenchmark { - // Test data (same as JVM benchmark for comparable results) + // Test data (same across all 3 platform benchmarks for comparability) private val privKey = hexToBytes("67E56582298859DDAE725F972992A07C6C4FB9F62A8FFF58CE3CA926A1063530") private val msg32 = hexToBytes("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89") private val auxRand = hexToBytes("0000000000000000000000000000000000000000000000000000000000000001") @@ -51,8 +58,8 @@ class Secp256k1NativeBenchmark { private val xOnlyPub = pubKey.copyOfRange(1, 33) private val sig = Secp256k1.signSchnorr(msg32, privKey, auxRand) private val privKey2 = hexToBytes("3982F19BEF1615BCCFBB05E321C10E1D4CBA3DF0E841C2E41EEB6016347653C3") - private val h02 = byteArrayOf(0x02) private val pub2xOnly = hexToBytes("c2f9d9948dc8c7c38321e4b85c8558872eafa0641cd269db76848a6073e69133") + private val h02 = byteArrayOf(0x02) // ============================================================ // Benchmark runner @@ -65,8 +72,6 @@ class Secp256k1NativeBenchmark { ) { val opsPerSec get() = iterations * 1_000_000_000L / nanos val nsPerOp get() = nanos / iterations - - override fun toString(): String = "$name: ${nsPerOp}ns/op ($opsPerSec ops/s)" } private inline fun bench( @@ -75,7 +80,7 @@ class Secp256k1NativeBenchmark { iterations: Int, crossinline op: () -> Unit, ): BenchResult { - // Warmup (LLVM AOT doesn't need warmup, but keeps methodology consistent) + // Warmup (LLVM AOT doesn't JIT, but warms up caches and branch predictors) repeat(warmup) { op() } val mark = TimeSource.Monotonic.markNow() @@ -85,8 +90,26 @@ class Secp256k1NativeBenchmark { return BenchResult(name, elapsed, iterations) } + private fun printResults( + title: String, + results: List, + ) { + println() + println("=".repeat(80)) + println(title) + println("=".repeat(80)) + for (r in results) { + println( + " ${r.name.padEnd(25)} ${ + r.nsPerOp.toString().padStart(10) + } ns/op ${r.opsPerSec.toString().padStart(8)} ops/s", + ) + } + println("=".repeat(80)) + } + // ============================================================ - // Individual benchmarks + // Individual benchmarks (same operations as JVM and Android) // ============================================================ @Test @@ -96,41 +119,28 @@ class Secp256k1NativeBenchmark { val results = mutableListOf() - // --- verifySchnorr --- + // --- verifySchnorr (same pubkey = cache-warm, typical Nostr pattern) --- results += bench("verifySchnorr", 2000, 5000) { Secp256k1.verifySchnorr(sig, msg32, xOnlyPub) } - // --- signSchnorr --- + // --- signSchnorr (derives pubkey each time) --- results += bench("signSchnorr", 1000, 3000) { Secp256k1.signSchnorr(msg32, privKey, auxRand) } - // --- signSchnorr (cached pubkey) --- + // --- signSchnorr (cached pubkey — skips G multiplication for pubkey derivation) --- results += bench("signSchnorr (cached pk)", 1000, 5000) { Secp256k1.signSchnorrWithPubKey(msg32, privKey, pubKey, auxRand) } - // --- pubkeyCreate --- + // --- compressedPubKeyFor (create + compress combined) --- results += - bench("pubkeyCreate", 1000, 5000) { - Secp256k1.pubkeyCreate(privKey) - } - - // --- pubKeyCompress --- - val uncompressed = Secp256k1.pubkeyCreate(privKey) - results += - bench("pubKeyCompress", 2000, 50000) { - Secp256k1.pubKeyCompress(uncompressed) - } - - // --- privKeyTweakAdd --- - results += - bench("privKeyTweakAdd", 1000, 50000) { - Secp256k1.privKeyTweakAdd(privKey, privKey2) + bench("compressedPubKeyFor", 1000, 5000) { + Secp256k1.pubKeyCompress(Secp256k1.pubkeyCreate(privKey)) } // --- secKeyVerify --- @@ -139,31 +149,56 @@ class Secp256k1NativeBenchmark { Secp256k1.secKeyVerify(privKey) } - // --- compressedPubKeyFor (create + compress) --- + // --- privKeyTweakAdd --- results += - bench("compressedPubKeyFor", 1000, 5000) { - Secp256k1.pubKeyCompress(Secp256k1.pubkeyCreate(privKey)) + bench("privKeyTweakAdd", 1000, 50000) { + Secp256k1.privKeyTweakAdd(privKey, privKey2) } - // --- ecdhXOnly --- + // --- ecdhXOnly (Nostr NIP-04/NIP-44 ECDH path) --- results += bench("ecdhXOnly (Nostr)", 1000, 3000) { Secp256k1.ecdhXOnly(pub2xOnly, privKey) } - // --- pubKeyTweakMul --- - results += - bench("pubKeyTweakMul", 1000, 3000) { - Secp256k1.pubKeyTweakMul(h02 + pub2xOnly, privKey) - } + printResults("secp256k1 Benchmark: Kotlin/Native (LLVM AOT) on linuxX64", results) - // Print results + // ==================== Batch verification ==================== + // Same pubkey, n events — the typical Nostr pattern (feed from one author). println() - println("=".repeat(80)) - println("secp256k1 Benchmark: Kotlin/Native (LLVM AOT) on ${getArch()}") - println("=".repeat(80)) - for (r in results) { - println(" ${r.name.padEnd(25)} ${r.nsPerOp.toString().padStart(10)} ns/op ${r.opsPerSec.toString().padStart(8)} ops/s") + for (batchSize in intArrayOf(4, 8, 16, 32)) { + val sigs = mutableListOf() + val msgs = mutableListOf() + for (i in 0 until batchSize) { + val m = ByteArray(32) { (i * 7 + it).toByte() } + sigs.add(Secp256k1.signSchnorr(m, privKey, auxRand)) + msgs.add(m) + } + // Warmup + repeat(500) { + for (j in 0 until batchSize) Secp256k1.verifySchnorr(sigs[j], msgs[j], xOnlyPub) + } + repeat(500) { Secp256k1.verifySchnorrBatch(xOnlyPub, sigs, msgs) } + // Time individual + val iters = 1000 + val indivMark = TimeSource.Monotonic.markNow() + repeat(iters) { + for (j in 0 until batchSize) Secp256k1.verifySchnorr(sigs[j], msgs[j], xOnlyPub) + } + val indivNs = indivMark.elapsedNow().inWholeNanoseconds + val indivPerEvent = iters.toLong() * batchSize * 1_000_000_000L / indivNs + // Time batch + val batchMark = TimeSource.Monotonic.markNow() + repeat(iters) { Secp256k1.verifySchnorrBatch(xOnlyPub, sigs, msgs) } + val batchNs = batchMark.elapsedNow().inWholeNanoseconds + val batchPerEvent = iters.toLong() * batchSize * 1_000_000_000L / batchNs + val speedup = indivNs.toDouble() / batchNs.toDouble() + println( + " batch(${batchSize.toString().padStart(2)}): " + + "individual ${indivPerEvent.toString().padStart(7)} ev/s " + + "batch ${batchPerEvent.toString().padStart(7)} ev/s " + + "speedup ${((speedup * 10).toLong() / 10.0)}x", + ) } println("=".repeat(80)) println() @@ -175,6 +210,8 @@ class Secp256k1NativeBenchmark { @Test fun benchmarkFieldOps() { + // Use result-dependent chains to prevent LLVM from hoisting constant computations + // out of the loop (dead code elimination risk with constant inputs). val a = U256.fromBytes(hexToBytes("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")) val b = U256.fromBytes(hexToBytes("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")) val out = LongArray(4) @@ -183,27 +220,32 @@ class Secp256k1NativeBenchmark { val results = mutableListOf() // --- FieldP.mul (the hottest operation) --- + // Uses `out` as both output and next input to create a data dependency chain. + a.copyInto(out) results += bench("FieldP.mul", 5000, 100000) { - FieldP.mul(out, a, b, w) + FieldP.mul(out, out, b, w) } // --- FieldP.sqr --- + a.copyInto(out) results += bench("FieldP.sqr", 5000, 100000) { - FieldP.sqr(out, a, w) + FieldP.sqr(out, out, w) } // --- FieldP.add --- + a.copyInto(out) results += bench("FieldP.add", 5000, 500000) { - FieldP.add(out, a, b) + FieldP.add(out, out, b) } // --- FieldP.sub --- + a.copyInto(out) results += bench("FieldP.sub", 5000, 500000) { - FieldP.sub(out, a, b) + FieldP.sub(out, out, b) } // --- FieldP.inv --- @@ -212,41 +254,26 @@ class Secp256k1NativeBenchmark { FieldP.inv(out, a) } - // --- unsignedMultiplyHigh --- - var sink = 0L + // --- unsignedMultiplyHigh (with varying input to prevent hoisting) --- + var hiSink = 0L results += bench("unsignedMultiplyHigh", 10000, 1000000) { - sink = unsignedMultiplyHigh(a[0], b[0]) + hiSink = unsignedMultiplyHigh(a[0] xor hiSink, b[0]) } - // --- uLt --- - var bsink = false + // --- uLt (with varying input to prevent hoisting) --- + var ltSink = 0L results += bench("uLt", 10000, 1000000) { - bsink = uLt(a[0], b[0]) + ltSink = if (uLt(a[0] xor ltSink, b[0])) 1L else 0L } - println() - println("=".repeat(80)) - println("secp256k1 Field Micro-Benchmarks: Kotlin/Native (LLVM AOT) on ${getArch()}") - println("=".repeat(80)) - for (r in results) { - println(" ${r.name.padEnd(25)} ${r.nsPerOp.toString().padStart(10)} ns/op ${r.opsPerSec.toString().padStart(8)} ops/s") - } - println("=".repeat(80)) - println() + printResults("secp256k1 Field Micro-Benchmarks: Kotlin/Native (LLVM AOT) on linuxX64", results) - // Use sinks to prevent dead code elimination - assertTrue(sink != Long.MIN_VALUE || !bsink || true) + // Use sinks to prevent dead code elimination of the entire benchmark + assertTrue(hiSink != Long.MIN_VALUE || ltSink != Long.MIN_VALUE || out[0] != Long.MIN_VALUE) } - private fun getArch(): String = - try { - "linuxX64" - } catch (_: Exception) { - "unknown" - } - private fun hexToBytes(hex: String): ByteArray { val len = hex.length / 2 val result = ByteArray(len)