|
| 1 | +#!/usr/bin/python |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# |
| 5 | +# Copyright The SCons Foundation |
| 6 | +# |
| 7 | + |
| 8 | +""" |
| 9 | +Benchmark for the switch from "foo.find('key') == -1" and similar |
| 10 | +to using the membership operators "in" and "not in". |
| 11 | +This is currently a standalone test, not integrated into the bench/ |
| 12 | +mechanism for running such tests. |
| 13 | +
|
| 14 | +The operators are quite a bit faster, around 4x. |
| 15 | +""" |
| 16 | + |
| 17 | +import timeit |
| 18 | + |
| 19 | +# Sample string and substring to test |
| 20 | +sample_string = "This is a sample string for testing." |
| 21 | +substring = "sample" |
| 22 | +missingstring = "badger" |
| 23 | + |
| 24 | +def test_in_operator() -> bool: |
| 25 | + return substring in sample_string |
| 26 | + |
| 27 | +def test_not_in_operator() -> bool: |
| 28 | + return missingstring not in sample_string |
| 29 | + |
| 30 | +def test_find_method() -> bool: |
| 31 | + return sample_string.find(substring) != -1 |
| 32 | + |
| 33 | +def test_no_find_method() -> bool: |
| 34 | + return sample_string.find(missingstring) == -1 |
| 35 | + |
| 36 | +# Time the "in" membership test |
| 37 | +time_in = timeit.timeit(test_in_operator, number=10000000) |
| 38 | +time_not_in = timeit.timeit(test_not_in_operator, number=10000000) |
| 39 | + |
| 40 | +# Time the "find" method membership test |
| 41 | +time_find = timeit.timeit(test_find_method, number=10000000) |
| 42 | +time_no_find = timeit.timeit(test_no_find_method, number=10000000) |
| 43 | + |
| 44 | +# Print the results |
| 45 | +print(f'"in" operator time: {time_in:.6f} seconds') |
| 46 | +print(f'.find() method time: {time_find:.6f} seconds') |
| 47 | +print(f'"not in" operator time: {time_not_in:.6f} seconds') |
| 48 | +print(f'.find() method time: {time_no_find:.6f} seconds') |
| 49 | + |
0 commit comments