mobench_sdk/lib.rs
1//! # mobench-sdk
2//!
3//! [](https://crates.io/crates/mobench-sdk)
4//! [](https://docs.rs/mobench-sdk)
5//! [](https://github.com/worldcoin/mobile-bench-rs/blob/main/LICENSE)
6//!
7//! A mobile benchmarking SDK for Rust that provides the runtime, builders, and
8//! generated mobile runners used by the `mobench` CLI for local execution,
9//! BrowserStack benchmark runs, and local native profiling.
10//!
11//! ## Overview
12//!
13//! `mobench-sdk` provides a simple, declarative API for defining benchmarks that can
14//! run on mobile devices. It handles the timing/runtime layer, cross-compilation,
15//! FFI bindings, template generation, and mobile app packaging used by the CLI.
16//!
17//! ## Quick Setup Checklist
18//!
19//! Before using mobench-sdk, ensure your project is configured correctly:
20//!
21//! ### Required Cargo.toml entries
22//!
23//! ```toml
24//! [dependencies]
25//! mobench-sdk = "0.1"
26//! inventory = "0.3" # Required for benchmark registration
27//!
28//! [lib]
29//! # Required for mobile FFI - produces .so (Android) and .a (iOS)
30//! crate-type = ["cdylib", "staticlib", "lib"]
31//! ```
32//!
33//! ### When UniFFI is needed
34//!
35//! If you're creating custom FFI types for your benchmarks (custom errors, specs, etc.),
36//! you'll also need UniFFI:
37//!
38//! ```toml
39//! [dependencies]
40//! uniffi = { version = "0.28", features = ["cli"] }
41//! thiserror = "1.0" # For custom error types
42//! serde = { version = "1.0", features = ["derive"] } # For serialization
43//!
44//! [build-dependencies]
45//! uniffi = { version = "0.28", features = ["build"] }
46//! ```
47//!
48//! For most use cases, the SDK's built-in types are sufficient and UniFFI setup
49//! is handled automatically by `cargo mobench build`.
50//!
51//! ### Troubleshooting
52//!
53//! If benchmarks aren't being discovered:
54//! 1. Ensure functions are annotated with `#[benchmark]`
55//! 2. Ensure functions are `pub` (public visibility)
56//! 3. Ensure functions take no parameters and return `()`
57//! 4. Use the [`debug_benchmarks!`] macro to print registered benchmarks
58//!
59//! For complete integration instructions, see
60//! [BENCH_SDK_INTEGRATION.md](https://github.com/worldcoin/mobile-bench-rs/blob/main/BENCH_SDK_INTEGRATION.md)
61//!
62//! ## Quick Start
63//!
64//! ### 1. Add Dependencies
65//!
66//! ```toml
67//! [dependencies]
68//! mobench-sdk = "0.1"
69//! inventory = "0.3" # Required for benchmark registration
70//! ```
71//!
72//! ### 2. Define Benchmarks
73//!
74//! Use the [`#[benchmark]`](macro@benchmark) attribute to mark functions for benchmarking:
75//!
76//! ```ignore
77//! use mobench_sdk::benchmark;
78//!
79//! #[benchmark]
80//! fn my_expensive_operation() {
81//! let result = expensive_computation();
82//! std::hint::black_box(result); // Prevent optimization
83//! }
84//!
85//! #[benchmark]
86//! fn another_benchmark() {
87//! for i in 0..1000 {
88//! std::hint::black_box(i * i);
89//! }
90//! }
91//! ```
92//!
93//! ### 3. Build and Run
94//!
95//! Use the `mobench` CLI to build and run benchmarks:
96//!
97//! ```bash
98//! # Install the CLI
99//! cargo install mobench
100//!
101//! # Build for Android (outputs to target/mobench/)
102//! cargo mobench build --target android
103//!
104//! # Build for iOS
105//! cargo mobench build --target ios
106//!
107//! # Run on BrowserStack (use --release for smaller APK uploads)
108//! cargo mobench run --target android --function my_expensive_operation \
109//! --iterations 100 --warmup 10 --devices "Google Pixel 7-13.0" --release
110//!
111//! # Or capture a local native profile
112//! cargo mobench profile run --target android --provider local \
113//! --backend android-native --function my_expensive_operation
114//! ```
115//!
116//! ## Architecture
117//!
118//! The SDK consists of several components:
119//!
120//! | Module | Description |
121//! |--------|-------------|
122//! | [`timing`] | Core timing infrastructure (always available) |
123//! | [`registry`] | Runtime discovery of `#[benchmark]` functions (requires `full` feature) |
124//! | [`runner`] | Benchmark execution engine (requires `full` feature) |
125//! | [`builders`] | Android and iOS build automation (requires `full` feature) |
126//! | [`codegen`] | Mobile app template generation (requires `full` feature) |
127//! | [`types`] | Common types and error definitions |
128//!
129//! ## Crate Ecosystem
130//!
131//! The mobench ecosystem consists of three published crates:
132//!
133//! - **`mobench-sdk`** (this crate) - Core SDK library with timing harness and build automation
134//! - **[`mobench`](https://crates.io/crates/mobench)** - CLI tool for building and running benchmarks
135//! - **[`mobench-macros`](https://crates.io/crates/mobench-macros)** - `#[benchmark]` proc macro
136//!
137//! Note: The `mobench-runner` crate has been consolidated into this crate as the [`timing`] module.
138//!
139//! ## Feature Flags
140//!
141//! | Feature | Default | Description |
142//! |---------|---------|-------------|
143//! | `full` | Yes | Full SDK with build automation, templates, and registry |
144//! | `runner-only` | No | Minimal timing-only mode for mobile binaries |
145//!
146//! For mobile binaries where binary size matters, use `runner-only`:
147//!
148//! ```toml
149//! [dependencies]
150//! mobench-sdk = { version = "0.1", default-features = false, features = ["runner-only"] }
151//! ```
152//!
153//! ## Programmatic Usage
154//!
155//! You can also use the SDK programmatically:
156//!
157//! ### Using the Builder Pattern
158//!
159//! ```ignore
160//! use mobench_sdk::BenchmarkBuilder;
161//!
162//! let report = BenchmarkBuilder::new("my_benchmark")
163//! .iterations(100)
164//! .warmup(10)
165//! .run()?;
166//!
167//! println!("Mean: {} ns", report.samples.iter()
168//! .map(|s| s.duration_ns)
169//! .sum::<u64>() / report.samples.len() as u64);
170//! ```
171//!
172//! ### Using BenchSpec Directly
173//!
174//! ```ignore
175//! use mobench_sdk::{BenchSpec, run_benchmark};
176//!
177//! let spec = BenchSpec {
178//! name: "my_benchmark".to_string(),
179//! iterations: 50,
180//! warmup: 5,
181//! };
182//!
183//! let report = run_benchmark(spec)?;
184//! println!("Collected {} samples", report.samples.len());
185//! ```
186//!
187//! ### Discovering Benchmarks
188//!
189//! ```ignore
190//! use mobench_sdk::{discover_benchmarks, list_benchmark_names};
191//!
192//! // Get all registered benchmark names
193//! let names = list_benchmark_names();
194//! for name in names {
195//! println!("Found benchmark: {}", name);
196//! }
197//!
198//! // Get full benchmark function info
199//! let benchmarks = discover_benchmarks();
200//! for bench in benchmarks {
201//! println!("Benchmark: {}", bench.name);
202//! }
203//! ```
204//!
205//! ## Building Mobile Apps
206//!
207//! The SDK includes builders for automating mobile app creation:
208//!
209//! ### Android Builder
210//!
211//! ```ignore
212//! use mobench_sdk::builders::AndroidBuilder;
213//! use mobench_sdk::{BuildConfig, BuildProfile, Target};
214//!
215//! let builder = AndroidBuilder::new(".", "my-bench-crate")
216//! .verbose(true)
217//! .output_dir("target/mobench"); // Default
218//!
219//! let config = BuildConfig {
220//! target: Target::Android,
221//! profile: BuildProfile::Release,
222//! incremental: true,
223//! };
224//!
225//! let result = builder.build(&config)?;
226//! println!("APK built at: {:?}", result.app_path);
227//! ```
228//!
229//! ### iOS Builder
230//!
231//! ```ignore
232//! use mobench_sdk::builders::{IosBuilder, SigningMethod};
233//! use mobench_sdk::{BuildConfig, BuildProfile, Target};
234//!
235//! let builder = IosBuilder::new(".", "my-bench-crate")
236//! .verbose(true);
237//!
238//! let config = BuildConfig {
239//! target: Target::Ios,
240//! profile: BuildProfile::Release,
241//! incremental: true,
242//! };
243//!
244//! let result = builder.build(&config)?;
245//! println!("xcframework built at: {:?}", result.app_path);
246//!
247//! // Package IPA for distribution
248//! let ipa_path = builder.package_ipa("BenchRunner", SigningMethod::AdHoc)?;
249//! ```
250//!
251//! ## Output Directory
252//!
253//! By default, all mobile artifacts are written to `target/mobench/`:
254//!
255//! ```text
256//! target/mobench/
257//! ├── android/
258//! │ ├── app/
259//! │ │ ├── src/main/jniLibs/ # Native .so libraries
260//! │ │ └── build/outputs/apk/ # Built APK
261//! │ └── ...
262//! └── ios/
263//! ├── sample_fns.xcframework/ # Built xcframework
264//! ├── BenchRunner/ # Xcode project
265//! └── BenchRunner.ipa # Packaged IPA
266//! ```
267//!
268//! This keeps generated files inside `target/`, following Rust conventions
269//! and preventing accidental commits of mobile project files.
270//!
271//! ## Platform Requirements
272//!
273//! ### Android
274//!
275//! - Android NDK (set `ANDROID_NDK_HOME` environment variable)
276//! - `cargo-ndk` (`cargo install cargo-ndk`)
277//! - Rust targets: `rustup target add aarch64-linux-android`
278//! - Optional extra ABI targets only when configured explicitly
279//!
280//! ### iOS
281//!
282//! - Xcode with command line tools
283//! - `uniffi-bindgen` (`cargo install --git https://github.com/mozilla/uniffi-rs --tag <uniffi-tag> uniffi-bindgen-cli --bin uniffi-bindgen`)
284//! - `xcodegen` (optional, `brew install xcodegen`)
285//! - Rust targets: `rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios`
286//!
287//! ## Best Practices
288//!
289//! ### Use `black_box` to Prevent Optimization
290//!
291//! Always wrap benchmark results with [`std::hint::black_box`] to prevent the
292//! compiler from optimizing away the computation:
293//!
294//! ```ignore
295//! #[benchmark]
296//! fn correct_benchmark() {
297//! let result = expensive_computation();
298//! std::hint::black_box(result); // Result is "used"
299//! }
300//! ```
301//!
302//! ### Avoid Side Effects
303//!
304//! Benchmarks should be deterministic and avoid I/O operations:
305//!
306//! ```ignore
307//! // Good: Pure computation
308//! #[benchmark]
309//! fn good_benchmark() {
310//! let data = vec![1, 2, 3, 4, 5];
311//! let sum: i32 = data.iter().sum();
312//! std::hint::black_box(sum);
313//! }
314//!
315//! // Avoid: File I/O adds noise
316//! #[benchmark]
317//! fn noisy_benchmark() {
318//! let data = std::fs::read_to_string("data.txt").unwrap(); // Don't do this
319//! std::hint::black_box(data);
320//! }
321//! ```
322//!
323//! ### Choose Appropriate Iteration Counts
324//!
325//! - **Warmup**: 5-10 iterations to warm CPU caches and JIT
326//! - **Iterations**: 50-100 for stable statistics
327//! - Mobile devices may have more variance than desktop
328//!
329//! ## License
330//!
331//! MIT License - see repository for details.
332
333#![cfg_attr(docsrs, feature(doc_cfg))]
334
335// Core timing module - always available
336pub mod timing;
337pub mod types;
338
339// UniFFI integration helpers
340// This module provides template types and conversion traits for UniFFI integration
341pub mod uniffi_types;
342
343// Unified FFI module for UniFFI integration
344pub mod ffi;
345
346// Full SDK modules - only with "full" feature
347#[cfg(feature = "full")]
348#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
349pub mod builders;
350#[cfg(feature = "full")]
351#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
352pub mod codegen;
353#[cfg(feature = "full")]
354#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
355pub mod registry;
356#[cfg(feature = "full")]
357#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
358pub mod runner;
359
360// Re-export the benchmark macro from bench-macros (only with full feature)
361#[cfg(feature = "full")]
362#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
363pub use mobench_macros::benchmark;
364
365// Re-export inventory so users don't need to add it as a separate dependency
366#[cfg(feature = "full")]
367#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
368pub use inventory;
369
370// Re-export key types for convenience (full feature)
371#[cfg(feature = "full")]
372#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
373pub use registry::{BenchFunction, discover_benchmarks, find_benchmark, list_benchmark_names};
374#[cfg(feature = "full")]
375#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
376pub use runner::{BenchmarkBuilder, run_benchmark};
377
378// Re-export types that are always available
379pub use types::{BenchError, BenchSample, BenchSpec, HarnessTimelineSpan, RunnerReport};
380
381// Re-export types that require full feature
382#[cfg(feature = "full")]
383#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
384pub use types::{
385 BuildConfig, BuildProfile, BuildResult, InitConfig, NativeLibraryArtifact, Target,
386};
387
388// Re-export timing types at the crate root for convenience
389pub use timing::{BenchSummary, SemanticPhase, TimingError, profile_phase, run_closure};
390
391/// Re-export of [`std::hint::black_box`] for preventing compiler optimizations.
392///
393/// Use this to ensure the compiler doesn't optimize away benchmark computations.
394pub use std::hint::black_box;
395
396/// Library version, matching `Cargo.toml`.
397///
398/// This can be used to verify SDK compatibility:
399///
400/// ```
401/// assert!(!mobench_sdk::VERSION.is_empty());
402/// ```
403pub const VERSION: &str = env!("CARGO_PKG_VERSION");
404
405/// Generates a debug function that prints all discovered benchmarks.
406///
407/// This macro is useful for debugging benchmark registration issues.
408/// It creates a function `_debug_print_benchmarks()` that you can call
409/// to see which benchmarks have been registered via `#[benchmark]`.
410///
411/// # Example
412///
413/// ```ignore
414/// use mobench_sdk::{benchmark, debug_benchmarks};
415///
416/// #[benchmark]
417/// fn my_benchmark() {
418/// std::hint::black_box(42);
419/// }
420///
421/// // Generate the debug function
422/// debug_benchmarks!();
423///
424/// fn main() {
425/// // Print all registered benchmarks
426/// _debug_print_benchmarks();
427/// // Output:
428/// // Discovered benchmarks:
429/// // - my_crate::my_benchmark
430/// }
431/// ```
432///
433/// # Troubleshooting
434///
435/// If no benchmarks are printed:
436/// 1. Ensure functions are annotated with `#[benchmark]`
437/// 2. Ensure functions are `pub` (public visibility)
438/// 3. Ensure the crate with benchmarks is linked into the binary
439/// 4. Check that `inventory` crate is in your dependencies
440#[cfg(feature = "full")]
441#[cfg_attr(docsrs, doc(cfg(feature = "full")))]
442#[macro_export]
443macro_rules! debug_benchmarks {
444 () => {
445 /// Prints all discovered benchmark functions to stdout.
446 ///
447 /// This function is generated by the `debug_benchmarks!()` macro
448 /// and is useful for debugging benchmark registration issues.
449 pub fn _debug_print_benchmarks() {
450 println!("Discovered benchmarks:");
451 let names = $crate::list_benchmark_names();
452 if names.is_empty() {
453 println!(" (none found)");
454 println!();
455 println!("Troubleshooting:");
456 println!(" 1. Ensure functions are annotated with #[benchmark]");
457 println!(" 2. Ensure functions are pub (public visibility)");
458 println!(" 3. Ensure the crate with benchmarks is linked into the binary");
459 println!(" 4. Check that 'inventory' crate is in your dependencies");
460 } else {
461 for name in names {
462 println!(" - {}", name);
463 }
464 }
465 }
466 };
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472
473 #[test]
474 fn test_version_is_set() {
475 assert!(!VERSION.is_empty());
476 }
477
478 #[cfg(feature = "full")]
479 #[test]
480 fn test_discover_benchmarks_compiles() {
481 // This test just ensures the function is accessible
482 let _benchmarks = discover_benchmarks();
483 }
484}