Skip to content

Instantly share code, notes, and snippets.

@sgf-dma
Last active January 26, 2023 12:48
Show Gist options
  • Save sgf-dma/095f52126ad7c7c34e6e3cea1a75178e to your computer and use it in GitHub Desktop.
Save sgf-dma/095f52126ad7c7c34e6e3cea1a75178e to your computer and use it in GitHub Desktop.
import dis
import cProfile
import timeit
def f1():
global y
global x
k = y / x
return k
def f2():
global y
global x
if y == 0:
k = 0
else:
k = y / x
return k
y = 3
x = 1.7
print("=" * 4, "байткод и спрофиль", "=" * 30)
print("f1(): ")
dis.dis(f1)
cProfile.run('f1')
print("f2(): ")
dis.dis(f2)
cProfile.run('f2')
rounds = 5000000
print("=" * 4, f"timeit: ненулевые значения, {rounds} проходов")
y = 3
x = 1.7
print("f1: ", timeit.timeit(lambda: f1(), number=rounds))
print("f2: ", timeit.timeit(lambda: f2(), number=rounds))
print("=" * 4, f"timeit: y == 0, {rounds} проходов")
y = 0
x = 1.7
print("f1: ", timeit.timeit(lambda: f1(), number=rounds))
print("f2: ", timeit.timeit(lambda: f2(), number=rounds))
print("=" * 4, "timeit: фибоначчи")
def f1(rst):
global fib_n
k = fib(fib_n, rst) / fib(fib_n, False)
return k
def f2(rst):
global fib_n
y = fib(fib_n, rst)
if y == 0:
k = 0
else:
x = fib(fib_n, False)
k = y / x
return k
def fib(n, rst):
if n == 0:
return 0
if n == 1:
if rst:
return 0
return 1
return fib(n -1, rst) + fib(n - 2, rst)
fib_n = 33
rounds = 3
print(f"Фибоначчи до {fib_n}:", timeit.timeit(lambda: fib(fib_n, False), number=1))
print(f"Фибоначчи до {fib_n} (сброс в 0 в конце):", timeit.timeit(lambda: fib(fib_n, True), number=1))
print("=" * 4, f"timeit: фибоначчи, ненулевые значения, {rounds} проходов")
print(timeit.timeit(lambda: f1(False), number=3))
print(timeit.timeit(lambda: f2(False), number=3))
print("=" * 4, f"timeit: факториал, y == 0, {rounds} проходов")
print(timeit.timeit(lambda: f1(True), number=3))
print(timeit.timeit(lambda: f2(True), number=3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment