2016-05-04 23 views
1

我一直在試圖找到以下函數的時序,該函數用於查找串口上連接的ZigBee模塊的地址。但是當我試圖找到使用timeit.Timer()方法的時機。它沒有迴應執行所需的時間。在Zigbee python模塊中查找函數的時序

from xbee import ZigBee 
from timeit import TImer 
import serial 

def ByteToHex(bytestring): 
    return ''.join(["%02X" % ord(x) for x in bytestring]).strip() 

def self_add_tx(): 
    s = serial.Serial('COM12', 9600) 
    xb = ZigBee(s) 
    xb.send('at', 
      command='SH')      
    self_frame_h = xb.wait_read_frame() 
    self_addh = self_frame_h['parameter'] 

    xb.send('at', 
      command='SL')      
    self_frame_l = xb.wait_read_frame() 
    s.close() 
    self_addl = self_frame_l['parameter'] 
    self_add = self_addh + self_addl    
    return ByteToHex(self_add) 

print Timer(self_add_tx()).timeit() 

當我執行程序時,它給我以下錯誤:

Traceback (most recent call last): 
    File "I:/HUB/Python_learning/gateway_url_pi/gateway_url_pi_865_mhz/test3.py", line 24, in <module> 
    print Timer(self_add_tx()).timeit() 
    File "C:\Python27\lib\timeit.py", line 129, in __init__ 
    compile(setup + '\n' + stmt, dummy_src_name, "exec") 
    File "<timeit-src>", line 2 
    0013A20040EA6DEC 
       ^
SyntaxError: invalid syntax 

我無法umderstand錯誤。有誰知道這個問題?我的代碼完美地運行,沒有這個Timer.timeit()

回答

0

您需要將函數作爲字符串傳遞給Timer()。在你當前的語法中,它執行self_add_tx()並將結果傳遞給Timer()執行。

試試這個語法來代替:

print Timer('self_add_tx()').timeit() 
+0

感謝您的回答。但它仍然沒有給我執行所需的時間。它顯示了「Traceback」(最近一次調用最後一次): 文件「I:/HUB/Python_learning/gateway_url_pi/gateway_url_pi_865_mhz/test3.py」,第24行,在 print Timer('self_add_tx()')。timeit() 文件「」,第6行,內部爲 NameError:全局名稱'012:'Python27 \ lib \ timeit.py',第201行,在timeit timing = self.inner(it,self.timer) self_add_tx'未定義' – abhi1610