Rollup merge of #128166 - ChaiTRex:isqrt, r=tgross35 · patricklam/verify-rust-std@374229a (original) (raw)

``

1

`+

use rand::Rng;

`

``

2

`+

use test::{black_box, Bencher};

`

``

3

+

``

4

`+

macro_rules! int_sqrt_bench {

`

``

5

`+

($t:ty, predictable:ident,predictable:ident, predictable:ident,random:ident, randomsmall:ident,random_small:ident, randomsmall:ident,random_uniform:ident) => {

`

``

6

`+

#[bench]

`

``

7

`+

fn $predictable(bench: &mut Bencher) {

`

``

8

`+

bench.iter(|| {

`

``

9

`+

for n in 0..(<$t>::BITS / 8) {

`

``

10

`+

for i in 1..=(100 as $t) {

`

``

11

`+

let x = black_box(i << (n * 8));

`

``

12

`+

black_box(x.isqrt());

`

``

13

`+

}

`

``

14

`+

}

`

``

15

`+

});

`

``

16

`+

}

`

``

17

+

``

18

`+

#[bench]

`

``

19

`+

fn $random(bench: &mut Bencher) {

`

``

20

`+

let mut rng = crate::bench_rng();

`

``

21

`+

/* Exponentially distributed random numbers from the whole range of the type. */

`

``

22

`+

let numbers: Vec<$t> =

`

``

23

`+

(0..256).map(|_| rng.gen::<$t>() >> rng.gen_range(0..<$t>::BITS)).collect();

`

``

24

`+

bench.iter(|| {

`

``

25

`+

for x in &numbers {

`

``

26

`+

black_box(black_box(x).isqrt());

`

``

27

`+

}

`

``

28

`+

});

`

``

29

`+

}

`

``

30

+

``

31

`+

#[bench]

`

``

32

`+

fn $random_small(bench: &mut Bencher) {

`

``

33

`+

let mut rng = crate::bench_rng();

`

``

34

`+

/* Exponentially distributed random numbers from the range 0..256. */

`

``

35

`+

let numbers: Vec<$t> =

`

``

36

`+

(0..256).map(|_| (rng.gen::() >> rng.gen_range(0..u8::BITS)) as $t).collect();

`

``

37

`+

bench.iter(|| {

`

``

38

`+

for x in &numbers {

`

``

39

`+

black_box(black_box(x).isqrt());

`

``

40

`+

}

`

``

41

`+

});

`

``

42

`+

}

`

``

43

+

``

44

`+

#[bench]

`

``

45

`+

fn $random_uniform(bench: &mut Bencher) {

`

``

46

`+

let mut rng = crate::bench_rng();

`

``

47

`+

/* Exponentially distributed random numbers from the whole range of the type. */

`

``

48

`+

let numbers: Vec<$t> = (0..256).map(|_| rng.gen::<$t>()).collect();

`

``

49

`+

bench.iter(|| {

`

``

50

`+

for x in &numbers {

`

``

51

`+

black_box(black_box(x).isqrt());

`

``

52

`+

}

`

``

53

`+

});

`

``

54

`+

}

`

``

55

`+

};

`

``

56

`+

}

`

``

57

+

``

58

`+

int_sqrt_bench! {u8, u8_sqrt_predictable, u8_sqrt_random, u8_sqrt_random_small, u8_sqrt_uniform}

`

``

59

`+

int_sqrt_bench! {u16, u16_sqrt_predictable, u16_sqrt_random, u16_sqrt_random_small, u16_sqrt_uniform}

`

``

60

`+

int_sqrt_bench! {u32, u32_sqrt_predictable, u32_sqrt_random, u32_sqrt_random_small, u32_sqrt_uniform}

`

``

61

`+

int_sqrt_bench! {u64, u64_sqrt_predictable, u64_sqrt_random, u64_sqrt_random_small, u64_sqrt_uniform}

`

``

62

`+

int_sqrt_bench! {u128, u128_sqrt_predictable, u128_sqrt_random, u128_sqrt_random_small, u128_sqrt_uniform}

`