原本以为速度会很慢,但测试结果十分令人鼓舞。在模式字符串未编译和已编译的情况下,Core i5-3210M处理器,单核速度达到了90万每秒和180万每秒。
import re
import time
pattern = '/devices/([^/]+)/([^/]+)'
compiled_pattern = re.compile(pattern)
test_rounds = 1000000
begin_time = time.time()
for i in range(test_rounds):
re.match(pattern, '/devices/sn_201312201560/uplink_frequency')
re.match(pattern, '/alarm/system')
elapsed_time = time.time() - begin_time
print(test_rounds * 2 / elapsed_time)
begin_time = time.time()
for i in range(test_rounds):
compiled_pattern.match('/devices/sn_201312201560/uplink_frequency')
compiled_pattern.match('/alarm/system')
elapsed_time = time.time() - begin_time
print(test_rounds * 2 / elapsed_time)