Last active
January 27, 2022 15:25
-
-
Save leogregianin/187c91d5443425f83e132a831e5c6b0d to your computer and use it in GitHub Desktop.
String filter performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import timeit | |
| def so_numeros_filter_lambda(texto): | |
| return ''.join(filter(lambda c: ord(c) in range(48, 58), texto)) | |
| def so_numeros_filter(texto): | |
| return ''.join(filter(str.isdigit, str(texto))) | |
| def so_numeros_listcomp(texto): | |
| return ''.join(c for c in texto if c.isdigit()) | |
| if __name__ == '__main__': | |
| time_so_numeros_filter_lambda = timeit.repeat( | |
| "so_numeros_filter_lambda('abc123456789def')", | |
| "from __main__ import so_numeros_filter_lambda", | |
| number=100000, | |
| repeat=5 | |
| ) | |
| time_so_numeros_filter = timeit.repeat( | |
| "so_numeros_filter('abc123456789def')", | |
| "from __main__ import so_numeros_filter", | |
| number=100000, | |
| repeat=5 | |
| ) | |
| time_so_numeros_listcomp = timeit.repeat( | |
| "so_numeros_listcomp('abc123456789def')", | |
| "from __main__ import so_numeros_listcomp", | |
| number=100000, | |
| repeat=5 | |
| ) | |
| print(f"so_numeros_filter_lambda={time_so_numeros_filter_lambda}") | |
| print(f"so_numeros_filter={time_so_numeros_filter}") | |
| print(f"so_numeros_listcomp={time_so_numeros_listcomp}") | |
| """ | |
| Result: | |
| so_numeros_filter_lambda=[0.6283188000088558, 0.5636512000346556, 0.5076404000283219, 0.5592665000003763, 0.4986145999864675] | |
| so_numeros_filter=[0.13521809998201206, 0.13535850000334904, 0.13656399998581037, 0.13404849998187274, 0.13291869999375194] | |
| so_numeros_listcomp=[0.12611449998803437, 0.1259357999661006, 0.12925290002021939, 0.12566810002317652, 0.12582770001608878] | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment