具有相似逻辑的功能时差

时间:2015-10-06 04:37:38

标签: python python-2.7

我正在编写脚本来测试sql-server DB。试图以最佳方式做到这一点并用sqlite玩弄。
代码片段只是DB查询与预先确定的值的比较,在两种不同的方法中进行,但类似的逻辑,
a)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

1 个答案:

答案 0 :(得分:0)

您应该可以使用timeit模块(https://docs.python.org/3.5/library/timeit.html),因为它在基准测试方面要比time好得多。

但我认为每个SQL命令都有一些info命令可以在实际执行后调用,并打印该代码的状态以及执行所需的时间 - 这将比timeit更准确。

但是由于我很长时间没有使用过sql,所以我无法向你提供更多信息。