combinations.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. use criterion::{black_box, criterion_group, criterion_main, Criterion};
  2. use itertools::Itertools;
  3. // approximate 100_000 iterations for each combination
  4. const N1: usize = 100_000;
  5. const N2: usize = 448;
  6. const N3: usize = 86;
  7. const N4: usize = 41;
  8. const N14: usize = 21;
  9. fn comb_for1(c: &mut Criterion) {
  10. c.bench_function("comb for1", move |b| {
  11. b.iter(|| {
  12. for i in 0..N1 {
  13. black_box(vec![i]);
  14. }
  15. })
  16. });
  17. }
  18. fn comb_for2(c: &mut Criterion) {
  19. c.bench_function("comb for2", move |b| {
  20. b.iter(|| {
  21. for i in 0..N2 {
  22. for j in (i + 1)..N2 {
  23. black_box(vec![i, j]);
  24. }
  25. }
  26. })
  27. });
  28. }
  29. fn comb_for3(c: &mut Criterion) {
  30. c.bench_function("comb for3", move |b| {
  31. b.iter(|| {
  32. for i in 0..N3 {
  33. for j in (i + 1)..N3 {
  34. for k in (j + 1)..N3 {
  35. black_box(vec![i, j, k]);
  36. }
  37. }
  38. }
  39. })
  40. });
  41. }
  42. fn comb_for4(c: &mut Criterion) {
  43. c.bench_function("comb for4", move |b| {
  44. b.iter(|| {
  45. for i in 0..N4 {
  46. for j in (i + 1)..N4 {
  47. for k in (j + 1)..N4 {
  48. for l in (k + 1)..N4 {
  49. black_box(vec![i, j, k, l]);
  50. }
  51. }
  52. }
  53. }
  54. })
  55. });
  56. }
  57. fn comb_c1(c: &mut Criterion) {
  58. c.bench_function("comb c1", move |b| {
  59. b.iter(|| {
  60. for combo in (0..N1).combinations(1) {
  61. black_box(combo);
  62. }
  63. })
  64. });
  65. }
  66. fn comb_c2(c: &mut Criterion) {
  67. c.bench_function("comb c2", move |b| {
  68. b.iter(|| {
  69. for combo in (0..N2).combinations(2) {
  70. black_box(combo);
  71. }
  72. })
  73. });
  74. }
  75. fn comb_c3(c: &mut Criterion) {
  76. c.bench_function("comb c3", move |b| {
  77. b.iter(|| {
  78. for combo in (0..N3).combinations(3) {
  79. black_box(combo);
  80. }
  81. })
  82. });
  83. }
  84. fn comb_c4(c: &mut Criterion) {
  85. c.bench_function("comb c4", move |b| {
  86. b.iter(|| {
  87. for combo in (0..N4).combinations(4) {
  88. black_box(combo);
  89. }
  90. })
  91. });
  92. }
  93. fn comb_c14(c: &mut Criterion) {
  94. c.bench_function("comb c14", move |b| {
  95. b.iter(|| {
  96. for combo in (0..N14).combinations(14) {
  97. black_box(combo);
  98. }
  99. })
  100. });
  101. }
  102. criterion_group!(
  103. benches,
  104. comb_for1,
  105. comb_for2,
  106. comb_for3,
  107. comb_for4,
  108. comb_c1,
  109. comb_c2,
  110. comb_c3,
  111. comb_c4,
  112. comb_c14,
  113. );
  114. criterion_main!(benches);