#[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.
§Basic Usage
ⓘ
use mobench_sdk::benchmark;
#[benchmark]
fn fibonacci_bench() {
let result = fibonacci(30);
std::hint::black_box(result);
}§With Setup (setup runs once, not measured)
ⓘ
use mobench_sdk::benchmark;
fn setup_proof() -> ProofInput {
ProofInput::generate() // Expensive, not measured
}
#[benchmark(setup = setup_proof)]
fn verify_proof(input: &ProofInput) {
verify(&input.proof); // Only this is measured
}§With Per-Iteration Setup (for mutating benchmarks)
ⓘ
use mobench_sdk::benchmark;
fn generate_random_vec() -> Vec<i32> {
(0..1000).map(|_| rand::random()).collect()
}
#[benchmark(setup = generate_random_vec, per_iteration)]
fn sort_benchmark(data: Vec<i32>) {
let mut data = data;
data.sort();
std::hint::black_box(data);
}§With Setup and Teardown
ⓘ
use mobench_sdk::benchmark;
fn setup_db() -> Database { Database::connect("test.db") }
fn cleanup_db(db: Database) { db.close(); }
#[benchmark(setup = setup_db, teardown = cleanup_db)]
fn db_query(db: &Database) {
db.query("SELECT * FROM users");
}§Function Requirements
Without setup:
- Take no parameters
- Return
()(unit type)
With setup:
- Take exactly one parameter (reference to setup result, or owned for per_iteration)
- Return
()(unit type)
§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
}