# 基準和性能分析

## 基準測試是什麼？

Python模塊進行基準測試

``````import timeit
import time
def functionA():
print("Function A starts the execution:")
print("Function A completes the execution:")
def functionB():
print("Function B starts the execution")
print("Function B completes the execution")

start_time = timeit.default_timer()
functionA()
print(timeit.default_timer() - start_time)
start_time = timeit.default_timer()
functionB()
print(timeit.default_timer() - start_time)``````

``````Function A starts the execution:
Function A completes the execution:
0.0014599495514175942
Function B starts the execution
Function B completes the execution
0.0017024724827479076``````

### 使用裝飾器函數編寫計時器

``````import random
import time

def timer_func(func):
"""
A timer decorator
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
start = time.time()
value = func(*args, **kwargs)
end = time.time()
runtime = end - start
msg = "{func} took {time} seconds to complete its execution."
print(msg.format(func = func.__name__,time = runtime))
return value

return function_timer

@timer_func
def Myfunction():
for x in range(5):
sleep_time = random.choice(range(1,3))
time.sleep(sleep_time)

if __name__ == '__main__':
Myfunction()``````

``Myfunction took 8.000457763671875 seconds to complete its execution.``

### cProfile - 內置模塊

cProfile是一個用於分析的Python內置模塊。 該模塊是一個具有合理開銷的C擴展，適合分析長時間運行的程序。 運行後，它會記錄所有的功能和執行時間。 這是非常強大的，但有時難以解釋和操作。 在下面的例子中，我們在下面的代碼中使用cProfile -

``````def increment_global():

global x
x += 1

for _ in range(50000):
lock.acquire()
increment_global()
lock.release()

def main():
global x
x = 0

t1.start()
t2.start()

t1.join()
t2.join()

if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))``````

``````(base) D:\ProgramData>python -m cProfile thread_increment.py
x = 100000 after Iteration 0
x = 100000 after Iteration 1
x = 100000 after Iteration 2
x = 100000 after Iteration 3
x = 100000 after Iteration 4
3577 function calls (3522 primitive calls) in 1.688 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)

5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:103(release)
5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:143(__init__)
5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:147(__enter__)
… … … …``````

• `ncalls` - 這是要調用的數字值。
• `tottime` - 這是在給定函數中花費的總時間。
• `percall` - 它指的是`tottime`除以`ncalls`的商。
• `cumtime` - 這是在這個和所有子功能中累計的時間。 遞歸函數甚至是準確的。
• `percall` - 它是`cumtime`除以原始調用的商。
• `filename:lineno(function)` - 它基本上提供了每個函數的相應數據。
0 條評論，你可以發表評論，我們會進行改進