|
| 1 | +// SPDX-License-Identifier: CC0-1.0 |
| 2 | + |
| 3 | +use std::hint::black_box; |
| 4 | + |
| 5 | +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; |
| 6 | +use std::time::Duration; |
| 7 | + |
| 8 | +use chacha20_poly1305::{ChaCha20Poly1305, Key, Nonce}; |
| 9 | + |
| 10 | +fn bench_chacha20poly1305(c: &mut Criterion) { |
| 11 | + let mut g = c.benchmark_group("chacha20poly1305"); |
| 12 | + g.measurement_time(Duration::from_secs(5)).warm_up_time(Duration::from_secs(2)); |
| 13 | + |
| 14 | + for &size in &[128usize, 1024, 16 * 1024, 64 * 1024] { |
| 15 | + let key = Key::new([0u8; 32]); |
| 16 | + let nonce = Nonce::new([0u8; 12]); |
| 17 | + |
| 18 | + let pt = vec![0u8; size]; |
| 19 | + let aad: &[u8] = b"dummy_aad"; |
| 20 | + |
| 21 | + g.throughput(Throughput::Bytes(size as u64)); |
| 22 | + |
| 23 | + g.bench_function(BenchmarkId::new("encrypt_no_aad", size), |b| { |
| 24 | + b.iter(|| { |
| 25 | + let mut buf = pt.clone(); |
| 26 | + let cipher = ChaCha20Poly1305::new(key, nonce); |
| 27 | + let tag = cipher.encrypt(black_box(&mut buf), None); |
| 28 | + black_box(tag); |
| 29 | + }); |
| 30 | + }); |
| 31 | + |
| 32 | + g.bench_function(BenchmarkId::new("encrypt_with_aad", size), |b| { |
| 33 | + b.iter(|| { |
| 34 | + let mut buf = pt.clone(); |
| 35 | + let cipher = ChaCha20Poly1305::new(key, nonce); |
| 36 | + let tag = cipher.encrypt(black_box(&mut buf), Some(aad)); |
| 37 | + black_box(tag); |
| 38 | + }); |
| 39 | + }); |
| 40 | + |
| 41 | + let mut ct = pt.clone(); |
| 42 | + let tag = ChaCha20Poly1305::new(key, nonce).encrypt(&mut ct, Some(aad)); |
| 43 | + |
| 44 | + g.bench_function(BenchmarkId::new("decrypt_ok", size), |b| { |
| 45 | + b.iter(|| { |
| 46 | + let mut buf = ct.clone(); |
| 47 | + let cipher = ChaCha20Poly1305::new(key, nonce); |
| 48 | + let res = cipher.decrypt(black_box(&mut buf), tag, Some(aad)); |
| 49 | + black_box(res.unwrap()); |
| 50 | + }); |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + g.finish(); |
| 55 | +} |
| 56 | + |
| 57 | +criterion_group!(benches, bench_chacha20poly1305); |
| 58 | +criterion_main!(benches); |
0 commit comments