Profiling code for time
We will start by creating a short program that will calculate and display all prime numbers up to a particular number. Prime numbers are numbers that are only divisible by themselves and one.
We will start by taking a naïve approach first:
def check_if_prime(number):
result = True
for i in range(2, number):
if number % i == 0:
result = False
return result
This code will take every number from 2 to the number under test (without including it), and check whether the number is divisible. If at any point it is divisible, the number is not a prime number.
To calculate all the way from 1 to 5,000, to verify that we are not making any mistakes, we will include the first prime numbers lower than 100 and compare them. This is on GitHub, available as primes_1.py
at https://github.com/PacktPublishing/Python-Architecture-Patterns/blob/main/chapter_14_profiling/primes_1.py.
PRIMES = [1, 2, 3, 5, 7, 11, 13, 17, 19...