2015-10-06 65 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