Skip to content

Commit 8471eaa

Browse files
authored
Create Python timeit測量代碼運行時間問題.md
1 parent 1e2b898 commit 8471eaa

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Python timeit 測量代碼運行時間問題
2+
3+
## 問題
4+
5+
```python
6+
def is_unique_char(string):
7+
if len(string) > 256:
8+
return True
9+
10+
record = 0L
11+
12+
for ch in string:
13+
# print record
14+
ch_val = ord(ch)
15+
16+
if (record & (1 << ch_val)) > 0:
17+
return False
18+
19+
record |= (1 << ch_val)
20+
21+
return True
22+
23+
24+
import string
25+
s1 = string.ascii_letters + string.digits
26+
27+
28+
if __name__ == '__main__':
29+
import timeit
30+
print is_unique_char(s1)
31+
print timeit.timeit("is_unique_char(s1)",
32+
setup="from __main__ import is_unique_char, s1")
33+
```
34+
35+
代碼如上, `is_unique_char` 就是一個包含位運算的函數(具體作用不重要)
36+
運行代碼,秒出 `print is_unique_char(s1)` 的結果,但是 `timeit` 測量需要 30 多秒。
37+
38+
這是為什麼呢?會不會是因為位運算? 呃,先感謝大家解答🙏
39+
40+
問題出自 [segmentfault](https://segmentfault.com/q/1010000005924858/a-1020000005925103), by [neo1218](https://segmentfault.com/u/neo1218)
41+
42+
## 回答
43+
44+
簡單來說,`timeit` 會執行代碼 `1000000` 次...,當然要花很久囉。
45+
46+
這個 function 是用來測量某段代碼的平均運行時間,所以你必須除以他執行的次數。
47+
48+
我改了一下你的代碼並且用 `time.time` 測了一下:
49+
50+
```python
51+
# uc.py
52+
53+
import string
54+
55+
def is_unique_char(string):
56+
if len(string) > 256:
57+
return True
58+
59+
record = 0L
60+
61+
for ch in string:
62+
# print record
63+
ch_val = ord(ch)
64+
65+
if (record & (1 << ch_val)) > 0:
66+
return False
67+
68+
record |= (1 << ch_val)
69+
70+
return True
71+
72+
s1 = string.ascii_letters + string.digits
73+
```
74+
75+
```python
76+
import timeit
77+
import time
78+
from uc import is_unique_char, s1
79+
80+
if __name__ == '__main__':
81+
btime = time.time()
82+
is_unique_char(s1)
83+
etime = time.time()
84+
print etime - btime
85+
print timeit.timeit("is_unique_char(s1)", setup="from uc import is_unique_char, s1")/1000000
86+
```
87+
88+
結果:
89+
90+
```
91+
4.91142272949e-05
92+
2.89517600536e-05
93+
```
94+
95+
結果是單次的運行差不多...

0 commit comments

Comments
 (0)