Skip to content

Instantly share code, notes, and snippets.

@thuwarakeshm
Last active July 26, 2021 09:36
Show Gist options
  • Save thuwarakeshm/64fc4045c12911f7387e2a35bf75c448 to your computer and use it in GitHub Desktop.
Save thuwarakeshm/64fc4045c12911f7387e2a35bf75c448 to your computer and use it in GitHub Desktop.
import cProfile
...
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
cProfile.run("fib(20)")
import cProfile
...
with cProfile.Profile() as pr:
# Your normal script
print(fib(20))
print(fib(25))
print(fib(30))
pr.print_stats()
@taimr
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
from time import time
def taimr(func):
def inner(*args, **kwargs):
t1 = time()
res = func(*args, **kwargs)
t2 = time()
print(f"Your function executino took {t2-t1} seconds")
return res
return inner
@taimr
def count_primes(max_num):
count = 0
for num in range(max_num * 1000 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
count += 1
return count
@taimr
def skwer(n):
return n ** 2
print(count_primes(20))
print(skwer(20))
import timeit
from functools import partial
f = partial(fib, 25)
print(timeit.timeit(f, number=10))
import timeit
def fib(n=20):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(timeit.timeit(fib, number=10))
@taimr
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
tracemalloc.start()
snap1 = tracemalloc.take_snapshot()
fib(40)
snap2 = tracemalloc.take_snapshot()
top_stats = snap2.compare_to(snap1, "lineno")
for stat in top_stats:
print(stat)
import tracemalloc
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
tracemalloc.start()
for i in range(25, 35):
print(f"{i}th fibonacci number is, {fib(i)}")
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")
print("---------------------------------------------------------")
[print(stat) for stat in top_stats]
from time import time
def count_primes(max_num):
"""This function counts of prime numbers below the input value.
Input values are in thousands, ie. 40, is 40,000.
"""
t1 = time()
count = 0
for num in range(max_num * 1000 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
count += 1
t2 = time()
print(f"Counting prime numbers took {t2-t1} seconds")
return count
print(count_primes(20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment