2

# 基礎語法

``````@decorator
def function():
# doSomething
``````

`function`是一個函數，

# 例子- 測量函數執行的時間

``````def isPrime_V1(n):
return n>=2 and len([i for i in range(1,int(n**0.5)+1) if n%i==0])==1

def isPrime_V2(n):
return n>=2 and not any(n%i==0 for i in range(2,int(n**0.5+1)))

def isPrime_V3(n):
return n==2 or (n > 2 and n%2 and all(n%x for x in range(3,int(n**.5)+1,2)))
``````

``````import time

def isPrime_V1(n):
return n>=2 and len([i for i in range(1,int(n**0.5)+1) if n%i==0])==1

def isPrime_V2(n):
return n>=2 and not any(n%i==0 for i in range(2,int(n**0.5+1)))

def isPrime_V3(n):
return n==2 or (n > 2 and n%2 and all(n%x for x in range(3,int(n**.5)+1,2)))

tStart = time.time() #計時開始
print(isPrime_V1(2**31-1))
tEnd = time.time() #計時結束
print(f"第一個函數執行了{(tEnd - tStart):.4f}秒")

tStart = time.time() #計時開始
print(isPrime_V2(2**31-1))
tEnd = time.time() #計時結束
print(f"第二個函數執行了{(tEnd - tStart):.4f}秒")

tStart = time.time() #計時開始
print(isPrime_V3(2**31-1))
tEnd = time.time() #計時結束
print(f"第三個函數執行了{(tEnd - tStart):.4f}秒")
``````

``````import time
def measureTime(func, i):
tStart = time.time() #計時開始
print(func(i))
tEnd = time.time() #計時結束
print(f"{func.__name__} 總共執行了{(tEnd - tStart):.4f}秒")

def isPrime_V1(n):
return n>=2 and len([i for i in range(1,int(n**0.5)+1) if n%i==0])==1

def isPrime_V2(n):
return n>=2 and not any(n%i==0 for i in range(2,int(n**0.5+1)))

def isPrime_V3(n):
return n==2 or (n > 2 and n%2 and all(n%x for x in range(3,int(n**.5)+1,2)))

measureTime(isPrime_V1, 2**31-1)
measureTime(isPrime_V2, 2**31-1)
measureTime(isPrime_V3, 2**31-1)
``````

「測量時間」是附加功能，

``````import time
def measureTime(func):
def inner(*args):
tStart = time.time() #計時開始
res = func(*args)
tEnd = time.time() #計時結束
print(f"{func.__name__} 總共執行了{(tEnd - tStart):.4f}秒")
return res
return inner

@measureTime
def isPrime_V1(n):
return n>=2 and len([i for i in range(1,int(n**0.5)+1) if n%i==0])==1

@measureTime
def isPrime_V2(n):
return n>=2 and not any(n%i==0 for i in range(2,int(n**0.5+1)))

@measureTime
def isPrime_V3(n):
return n==2 or (n > 2 and n%2 and all(n%x for x in range(3,int(n**.5)+1,2)))

print(isPrime_V1(2**31-1))
print(isPrime_V2(2**31-1))
print(isPrime_V3(2**31-1))
``````

# 參考資料

### 1 則留言

1
samuel24
iT邦新手 5 級 ‧ 2020-07-05 08:27:46