---
# System prepended metadata

title: How To Setup Benchmarking Using Criterion

---

# How To Setup Benchmarking Using Criterion

```
cargo new <project_name>

cd <project_name>/
```

install criterion dependency as a dev dependency

```
cargo add criterion --dev
```

create a folder in your root dir `benches/`. ensure it is not in `src/`

```
mkdir benches
touch benches/<filename_bench.rs>

e.g. touch benches/variable_bench.rs
```
```
folder structure
-------------------------------
src/
|__  main.rs
benches/
|__  variable_bench.rs
```

in your `bench/variable_bench.rs` add this code snippet for test purpose:

```
use criterion::{criterion_group, criterion_main, Criterion};

fn stack_variable(c: &mut Criterion) {
    c.bench_function("stack integer", |b| {
        b.iter(|| {
            let x = 42;
            x
        })
    });
}

fn heap_string(c: &mut Criterion) {
    c.bench_function("heap string", |b| {
        b.iter(|| {
            let s = String::from("Rust");
            s
        })
    });
}

fn clone_string(c: &mut Criterion) {
    c.bench_function("clone string", |b| {
        let s1 = String::from("Rust");
        b.iter(|| s1.clone())
    });
}

fn reference_borrow(c: &mut Criterion) {
    c.bench_function("reference borrow", |b| {
        let s1 = String::from("Rust");
        b.iter(|| {
            let s2 = &s1;
            s2
        })
    });
}

criterion_group!(benches, stack_variable, heap_string, clone_string, reference_borrow);
criterion_main!(benches);
```

in your `cargo.toml` add the following:
```
[[bench]]
name = "variable_bench"
harness = false
```

once all is set and done: run your benchmark using the command below:

`cargo bench`