Benchmark code for comparing 2 functions, with different length int values. Brian Kernighan's algorithm is consistently faster than using modulo_operator.
()
| 61 | |
| 62 | |
| 63 | def benchmark() -> None: |
| 64 | """ |
| 65 | Benchmark code for comparing 2 functions, with different length int values. |
| 66 | Brian Kernighan's algorithm is consistently faster than using modulo_operator. |
| 67 | """ |
| 68 | |
| 69 | def do_benchmark(number: int) -> None: |
| 70 | setup = "import __main__ as z" |
| 71 | print(f"Benchmark when {number = }:") |
| 72 | print(f"{get_set_bits_count_using_modulo_operator(number) = }") |
| 73 | timing = timeit( |
| 74 | f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup |
| 75 | ) |
| 76 | print(f"timeit() runs in {timing} seconds") |
| 77 | print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }") |
| 78 | timing = timeit( |
| 79 | f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})", |
| 80 | setup=setup, |
| 81 | ) |
| 82 | print(f"timeit() runs in {timing} seconds") |
| 83 | |
| 84 | for number in (25, 37, 58, 0): |
| 85 | do_benchmark(number) |
| 86 | print() |
| 87 | |
| 88 | |
| 89 | if __name__ == "__main__": |
no test coverage detected