回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<h2>为什么:内存:在sqlite中如此缓慢?</h2>
<p>我一直在尝试使用内存中的sqlite与基于磁盘的sqlite相比,是否有任何性能改进。基本上,我想用启动时间和内存来获得非常快速的查询,这些查询在应用程序过程中不会命中磁盘。</p>
<p>但是,下面的基准测试只给了我1.5倍的速度提升系数。在这里,我生成了1M行随机数据,并将其加载到同一个表的基于磁盘和内存的版本中。然后,我在两个数据库上运行随机查询,返回大约300k的大小集。我希望基于内存的版本要快得多,但如前所述,我只得到1.5倍的加速。</p>
<p>我尝试了其他几种大小的dbs和查询集;其优点是:内存:<em>似乎会随着db中行数的增加而增加。我不知道为什么优势这么小,尽管我有几个假设:</p>
<ul>
<li>使用的表不够大(成行):内存:一个巨大的赢家</li>
<li>更多的连接/表将使:memory:优势更加明显</li>
<li>在连接或操作系统级别上有某种缓存,这样以前的结果就可以以某种方式访问,从而破坏了基准</li>
<li>有一种隐藏的磁盘访问正在进行,我没有看到(我还没有尝试lsof,但我确实关闭了用于日志记录的PRAGMAs)</li>
</ul>
<p>我在这里做错什么了吗?关于原因的任何想法:记忆:不产生几乎即时的查找吗?以下是基准:</p>
<pre><code>==> sqlite_memory_vs_disk_benchmark.py <==
#!/usr/bin/env python
"""Attempt to see whether :memory: offers significant performance benefits.
"""
import os
import time
import sqlite3
import numpy as np
def load_mat(conn,mat):
c = conn.cursor()
#Try to avoid hitting disk, trading safety for speed.
#http://stackoverflow.com/questions/304393
c.execute('PRAGMA temp_store=MEMORY;')
c.execute('PRAGMA journal_mode=MEMORY;')
# Make a demo table
c.execute('create table if not exists demo (id1 int, id2 int, val real);')
c.execute('create index id1_index on demo (id1);')
c.execute('create index id2_index on demo (id2);')
for row in mat:
c.execute('insert into demo values(?,?,?);', (row[0],row[1],row[2]))
conn.commit()
def querytime(conn,query):
start = time.time()
foo = conn.execute(query).fetchall()
diff = time.time() - start
return diff
#1) Build some fake data with 3 columns: int, int, float
nn = 1000000 #numrows
cmax = 700 #num uniques in 1st col
gmax = 5000 #num uniques in 2nd col
mat = np.zeros((nn,3),dtype='object')
mat[:,0] = np.random.randint(0,cmax,nn)
mat[:,1] = np.random.randint(0,gmax,nn)
mat[:,2] = np.random.uniform(0,1,nn)
#2) Load it into both dbs & build indices
try: os.unlink('foo.sqlite')
except OSError: pass
conn_mem = sqlite3.connect(":memory:")
conn_disk = sqlite3.connect('foo.sqlite')
load_mat(conn_mem,mat)
load_mat(conn_disk,mat)
del mat
#3) Execute a series of random queries and see how long it takes each of these
numqs = 10
numqrows = 300000 #max number of ids of each kind
results = np.zeros((numqs,3))
for qq in range(numqs):
qsize = np.random.randint(1,numqrows,1)
id1a = np.sort(np.random.permutation(np.arange(cmax))[0:qsize]) #ensure uniqueness of ids queried
id2a = np.sort(np.random.permutation(np.arange(gmax))[0:qsize])
id1s = ','.join([str(xx) for xx in id1a])
id2s = ','.join([str(xx) for xx in id2a])
query = 'select * from demo where id1 in (%s) AND id2 in (%s);' % (id1s,id2s)
results[qq,0] = round(querytime(conn_disk,query),4)
results[qq,1] = round(querytime(conn_mem,query),4)
results[qq,2] = int(qsize)
#4) Now look at the results
print " disk | memory | qsize"
print "-----------------------"
for row in results:
print "%.4f | %.4f | %d" % (row[0],row[1],row[2])
</code></pre>
<p>这是结果。注意,对于相当大范围的查询大小,磁盘占用的内存大约是内存的1.5倍。</p>
<pre><code>[ramanujan:~]$python -OO sqlite_memory_vs_disk_clean.py
disk | memory | qsize
-----------------------
9.0332 | 6.8100 | 12630
9.0905 | 6.6953 | 5894
9.0078 | 6.8384 | 17798
9.1179 | 6.7673 | 60850
9.0629 | 6.8355 | 94854
8.9688 | 6.8093 | 17940
9.0785 | 6.6993 | 58003
9.0309 | 6.8257 | 85663
9.1423 | 6.7411 | 66047
9.1814 | 6.9794 | 11345
</code></pre>
<p>RAM相对于磁盘不应该几乎是即时的吗?这里出什么事了?</p>
<h2>编辑</h2>
<p>这里有一些好的建议。</p>
<p>我想我的主要观点是**可能没有办法:内存:<em>绝对更快</em>,但是有一种方法可以使磁盘访问相对较慢。</em>**</p>
<p>换言之,基准测试充分衡量了内存的实际性能,而不是磁盘的实际性能(例如,由于缓存大小pragma太大或因为我没有执行写操作)。当我有机会的时候,我会处理这些参数并发布我的发现。</p>
<p>也就是说,如果有人认为我可以从内存数据库中挤出更多的速度(而不是通过提高缓存大小和默认缓存大小,我会这么做),我会全神贯注。。。</p>