-
-
Save ya-boiko/cc98b0e3448fafcbbfb426e16e2984ac to your computer and use it in GitHub Desktop.
A script to test the speed of different arithmetic operations with float, integer and decimal values in Python
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
| """Testing the speed of different arithmetic operations with float, integer and decimal values in Python.""" | |
| from datetime import datetime | |
| from decimal import getcontext, Decimal | |
| from random import randint | |
| def get_random_pairs() -> tuple[float, float]: | |
| """Get a pair of random float values.""" | |
| return ( | |
| float(randint(1000, 10000) / 100), | |
| float(randint(1000, 10000) / 100), | |
| ) | |
| def arithmetic_operations(a, b) -> None: | |
| """Make arithmetic operations.""" | |
| _ = a + b | |
| _ = a - b | |
| _ = a * b | |
| _ = a / b | |
| _ = a // b | |
| _ = a % b | |
| _ = a ** b | |
| values: list[tuple] = [get_random_pairs() for _ in range(1_000_000)] | |
| # check of arithmetic operations with values of a float type | |
| start: datetime = datetime.now() | |
| for v1, v2 in values: | |
| arithmetic_operations(v1, v2) | |
| print(f"float: {datetime.now() - start}") | |
| # check of arithmetic operations with values of an integer type | |
| start: datetime = datetime.now() | |
| for v1, v2 in values: | |
| arithmetic_operations(int(v1), int(v2)) | |
| print(f"integer: {datetime.now() - start}") | |
| # check of arithmetic operations with values of a decimal type | |
| start: datetime = datetime.now() | |
| for v1, v2 in values: | |
| arithmetic_operations(Decimal(v1), Decimal(v2)) | |
| print(f"decimal: {datetime.now() - start}") | |
| # check of arithmetic operations with values of a decimal type with setting the number of significant digits | |
| getcontext().prec = 6 | |
| start: datetime = datetime.now() | |
| for v1, v2 in values: | |
| arithmetic_operations(Decimal(v1), Decimal(v2)) | |
| print(f"decimal [prec=6]: {datetime.now() - start}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment