benchmark

Attribute Macro benchmark 

Source
#[benchmark]
Available on crate feature full only.
Expand description

Marks a function as a benchmark for mobile execution.

This attribute macro registers the function in the global benchmark registry, making it discoverable and executable by the mobench runtime.

§Usage

use mobench_sdk::benchmark;

#[benchmark]
fn fibonacci_bench() {
    let result = fibonacci(30);
    std::hint::black_box(result);
}

§Function Requirements

The annotated function must:

  • Take no parameters
  • Return () (unit type)
  • Not panic during normal execution

§Best Practices

§Use black_box to Prevent Optimization

Always wrap results with [std::hint::black_box] to prevent the compiler from optimizing away the computation:

#[benchmark]
fn good_benchmark() {
    let result = compute_something();
    std::hint::black_box(result);  // Prevents optimization
}

§Avoid Side Effects

Benchmarks should be deterministic. Avoid:

  • File I/O
  • Network calls
  • Random number generation (unless seeded)
  • Global mutable state

§Keep Benchmarks Focused

Each benchmark should measure one specific operation:

// Good: Focused benchmark
#[benchmark]
fn benchmark_json_parse() {
    let json = r#"{"key": "value"}"#;
    let parsed: serde_json::Value = serde_json::from_str(json).unwrap();
    std::hint::black_box(parsed);
}

// Avoid: Multiple operations in one benchmark
#[benchmark]
fn benchmark_everything() {
    let json = create_json();  // Measured
    let parsed = parse_json(&json);  // Measured
    let serialized = serialize(parsed);  // Measured
    std::hint::black_box(serialized);
}

§Generated Code

The macro generates code equivalent to:

fn my_benchmark() {
    // Original function body
}

inventory::submit! {
    mobench_sdk::registry::BenchFunction {
        name: "my_crate::my_module::my_benchmark",
        invoke: |_args| {
            my_benchmark();
            Ok(())
        },
    }
}

§Discovering Benchmarks

Registered benchmarks can be discovered at runtime:

use mobench_sdk::{discover_benchmarks, list_benchmark_names};

// Get all benchmark names
for name in list_benchmark_names() {
    println!("Found: {}", name);
}

// Get full benchmark info
for bench in discover_benchmarks() {
    println!("Benchmark: {}", bench.name);
}