Here is our prime count program.
def count_primes(n):
count = 0
for num in range(2, n + 1):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
count += 1
return count
Using cProfile
we see that count_primes
is consuming the most time.
python3 -m cProfile -s cumtime python-prime-count.py
5 function calls in 0.397 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.397 0.397 {built-in method builtins.exec}
1 0.000 0.000 0.397 0.397 python-prime-count.py:3(<module>)
1 0.397 0.397 0.397 0.397 python-prime-count.py:3(count_primes)
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
![Screen Shot 2024-10-03 at 10 55 52 AM](https://private-user-images.githubusercontent.com/13820251/373403912-655039c9-c6a0-4b39-80ac-3ae1638345b9.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzkxOTcxNTcsIm5iZiI6MTczOTE5Njg1NywicGF0aCI6Ii8xMzgyMDI1MS8zNzM0MDM5MTItNjU1MDM5YzktYzZhMC00YjM5LTgwYWMtM2FlMTYzODM0NWI5LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTAyMTAlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwMjEwVDE0MTQxN1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTRiOTc1NDY4MzJkMzg5Y2E4NmE0YzRlZmFhYzQwMzFiNjZlZjU0MzQ5OWZiZjZmZmJiNTAxMTU5YzIyMDViZDcmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.S6cuPi4zLOhKihWhh1nO0xpKCIAnG-FrX5N3iUyeLnE)
Looking at count_primes
we see that the outer loop iterates from 2
to n + 1
and the inner loop checks if the current number num
is divisible by any number less than itself.
This is pretty much a brute-force method and is very inefficient.
Switch to the optimize-inner-loop
branch to see the inner loop optimization.