2015-10-06 61 views
0

我正在編寫測試sql-server數據庫的腳本。試圖以最佳方式做到這一點,並與SQLite玩弄。
代碼段只是DB查詢的比較預定值做,在兩種不同的方法,但類似的邏輯,
一個)TCOUNT()函數
B)newcount()和test_test()函數具有類似邏輯的函數的時間差異

我無法弄清楚爲什麼這段時間在代碼中發生了變化。或者這太不容忽視了?

import sqlite3 
import sys, time, re, timeit 
import pytest 

def timing(f): 
    def wrap(*args): 
     time1 = time.time() 
     ret = f(*args) 
     time2 = time.time() 
     print 'Function :%s took %0.3f ms' % (f.func_name, (time2-time1)*1000.0) 
     return ret 
    return wrap 

conn = sqlite3.connect(r'E:\Python_Projects\Demo\sqlite-DBS\newdb.db') 

@timing 
def tcount(): 
    table_list = ['Album', 'Artist', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist'] 
    count_query = """select count(*) from %s;""" 
    count = {'Album': 347, 'Playlist': 18, 'Artist': 275, 'MediaType': 5, 'Genre': 25, 'Invoice': 412, 'InvoiceLine': 2240, 'Employee': 8} 
    table_count = {} 
    for table in table_list: 
     try: 
      result = conn.execute(count_query % table)   
      for x in result: 
       table_count[table] = x[0] 
     except: 
      e = sys.exc_info()[0] 
      print e 
    return (table_count == count) 

@timing 
def newcount(): 
    table_list = ['Album', 'Artist', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist'] 
    count_query = """select count(*) from %s;""" 

    table_count = {} 
    for table in table_list: 
     try: 
      result = conn.execute(count_query % table)   
      for x in result: 
       table_count[table] = x[0] 
     except: 
      e = sys.exc_info()[0] 
      print e 
    return table_count 

@timing 
def test_test(): 
    count = {'Album': 347, 'Playlist': 18, 'Artist': 275, 'MediaType': 5, 'Genre': 25, 'Invoice': 412, 'InvoiceLine': 2240, 'Employee': 8} 
    return (newcount() == count) 


print tcount() 
print test_test() 
conn.close() 

輸出:

Function :tcount took 0.000 ms 
True 
Function :newcount took 0.000 ms 
Function :test_test took 16.000 ms 
True 

回答

0

您應該propably使用timeit模塊(https://docs.python.org/3.5/library/timeit.html),因爲它是遠遠超過time更好的標杆。

但我認爲每個SQL命令都有一些info命令,可以在實際執行後調用該命令並打印該代碼的狀態以及執行所花費的時間 - 這將比timeit更準確。

但是由於我很長一段時間沒有使用過sql,所以我無法給你更多的信息。

+0

感謝您的迴應,沒有查詢返回表中的表名和記錄數。我希望他們能夠在分期和決賽之間進行比較。所以,我正在使用字典。 – WoodChopper

+0

,你用'timeit'試過了嗎? – MSeifert

+0

我不熟悉如何去做。我會在完成後發佈更新。 – WoodChopper