gpt4 book ai didi

python - 为什么在这个简单的基准测试中 SQLite 比 Redis 快?

转载 作者:IT老高 更新时间:2023-10-28 22:23:25 26 4
gpt4 key购买 nike

我在本地机器上做了简单的性能测试,这是python脚本:

import redis
import sqlite3
import time

data = {}
N = 100000

for i in xrange(N):
key = "key-"+str(i)
value = "value-"+str(i)
data[key] = value

r = redis.Redis("localhost", db=1)
s = sqlite3.connect("testDB")
cs = s.cursor()

try:
cs.execute("CREATE TABLE testTable(key VARCHAR(256), value TEXT)")
except Exception as excp:
print str(excp)
cs.execute("DROP TABLE testTable")
cs.execute("CREATE TABLE testTable(key VARCHAR(256), value TEXT)")

print "[---Testing SQLITE---]"
sts = time.time()
for key in data:
cs.execute("INSERT INTO testTable VALUES(?,?)", (key, data[key]))
#s.commit()
s.commit()
ste = time.time()
print "[Total time of sql: %s]"%str(ste-sts)

print "[---Testing REDIS---]"
rts = time.time()
r.flushdb()# for empty db
for key in data:
r.set(key, data[key])
rte = time.time()
print "[Total time of redis: %s]"%str(rte-rts)

我希望 redis 执行得更快,但结果表明它要慢得多:

[---Testing SQLITE---]
[Total time of sql: 0.615846157074]
[---Testing REDIS---]
[Total time of redis: 10.9668009281]

那么,redis 是基于内存的,那么 sqlite 呢?为什么redis这么慢?什么时候需要使用redis,什么时候需要使用sqlite?

最佳答案

来自 redis documentation

Redis is a server: all commands involve network or IPC roundtrips. It is meaningless to compare it to embedded data stores such as SQLite, Berkeley DB, Tokyo/Kyoto Cabinet, etc ... because the cost of most operations is precisely dominated by network/protocol management.

这确实是有道理的,尽管在某些情况下这是对速度问题的承认。例如,在多个并行访问下,Redis 的性能可能比 sqlite 好得多。

适合工作的正确工具,有时是 redis,有时是 sqlite,有时是完全不同的东西。如果此速度测试正确显示了您的应用程序将实际执行的操作,那么 sqlite 将为您提供更好的服务,并且您执行此基准测试很好。

关于python - 为什么在这个简单的基准测试中 SQLite 比 Redis 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com