Rust 在 Ubuntu 上的性能测试实践
一 测试类型与工具选型
二 微基准测试 Criterion.rs
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "my_benchmarks"
harness = false
use criterion::{criterion_group, criterion_main, Criterion, BenchmarkId, black_box};
fn fib_rec(n: u64) -> u64 {
match n { 0 | 1 => 1, n => fib_rec(n - 1) + fib_rec(n - 2) }
}
fn fib_iter(n: u64) -> u64 {
let (mut a, mut b) = (0, 1);
for _ in 0..n { let c = a + b; a = b; b = c; }
b
}
fn bench_fib(c: &mut Criterion) {
let mut g = c.benchmark_group("Fibonacci");
for n in [10, 20, 30].iter() {
g.bench_with_input(BenchmarkId::new("Recursive", n), n, |b, &i| {
b.iter(|| fib_rec(black_box(i)))
});
g.bench_with_input(BenchmarkId::new("Iterative", n), n, |b, &i| {
b.iter(|| fib_iter(black_box(i)))
});
}
g.finish();
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);
三 HTTP 负载与压力测试
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
#[get("/api/hello")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello, World!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(hello))
.bind("127.0.0.1:8080")?
.run()
.await
}
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
stages: [
{ duration: '30s', target: 100 },
{ duration: '1m', target: 100 },
{ duration: '30s', target: 0 },
],
};
export default function () {
let res = http.get('http://localhost:8080/api/hello');
check(res, { 'status is 200': r => r.status === 200 });
sleep(1);
}
四 运行时与系统层分析
五 实践建议与常见瓶颈