执行许多删除似乎很慢(插入很好),我想知道是否有人知道为什么花了这么长时间
考虑下面的代码
import sqlite3
db = sqlite3.connect("mydb")
c = db.cursor()
c.execute("DROP TABLE IF EXISTS testing ")
c.execute("CREATE TABLE testing (val INTEGER);")
my_vals2 = [[x] for x in range(1,10000)]
def insertmany(vals):
c.executemany("INSERT INTO testing (val) VALUES (?)",vals)
db.commit()
def deletemany1(vals):
c.executemany("DELETE FROM testing WHERE val=?",vals)
db.commit()
def deletemany2(vals): #this is fastest even though im looping over to convert to strings and again to join ...
vals = ["'%s'"%v[0] for v in vals]
c.execute("DELETE FROM testing WHERE val IN (%s)"%",".join(vals))
#DELETE FROM TABLE WHERE x in (1,2,3...)
以及来自 ipython 的以下时间结果(timeit 给出了有趣的数据:/)
%time insertmany(my_vals2)
#CPU times: user 0.60 s, sys: 0.00 s, total: 0.60 s Wall time: 0.60 s
%time deletemany1(my_vals2)
#CPU times: user 3.58 s, sys: 0.00 s, total: 3.58 s Wall time: 3.58 s
%time deletemany2(my_vals2)
#CPU times: user 0.02 s, sys: 0.00 s, total: 0.02 s Wall time: 0.02 s
为了完整起见,这里是 timeit 结果(但我认为 timeit 在第二次测试中被打破(或者 ms 是一个不同的单位,然后是第一次测试))
%timeit insertmany(my_vals2)
#1 loops, best of 3: 358 ms per loop
%timeit deletemany1(my_vals2)
#1 loops, best of 3: 8.34 ms per loop <- this is not faster than the above!!!! (timeit lies?)
%timeit deletemany2(my_vals2)
#100 loops, best of 3: 2.3 ms per loop
那么,为什么 deletes 的 executemany 这么慢呢?