【发布时间】:2019-02-17 06:26:50
【问题描述】:
我需要使用 Python 3 在烧瓶应用程序中保存一次并多次加载一些大数组。我最初使用 json 库将这些数组存储在磁盘上。为了加快速度,我在同一台机器上使用 Redis 通过将数组序列化为 JSON 字符串来存储数组。我想知道为什么我没有得到任何改进(实际上在我使用的服务器上需要更多时间),而 Redis 将数据保存在 RAM 中。我猜 JSON 序列化没有优化,但我不知道如何加快速度:
import json
import redis
import os
import time
current_folder = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_folder, "my_file")
my_array = [1]*10000000
with open(file_path, 'w') as outfile:
json.dump(my_array, outfile)
start_time = time.time()
with open(file_path, 'r') as infile:
my_array = json.load(infile)
print("JSON from disk : ", time.time() - start_time)
r = redis.Redis()
my_array_as_string = json.dumps(my_array)
r.set("my_array_as_string", my_array_as_string)
start_time = time.time()
my_array_as_string = r.get("my_array_as_string")
print("Fetch from Redis:", time.time() - start_time)
start_time = time.time()
my_array = json.loads(my_array_as_string)
print("Parse JSON :", time.time() - start_time)
结果:
JSON from disk : 1.075700044631958
Fetch from Redis: 0.078125
Parse JSON : 1.0247752666473389
编辑:貌似从redis中获取其实很快,但是解析JSON却很慢。有没有办法在没有 JSON 序列化部分的情况下直接从 Redis 获取数组?这就是我们使用 pyMySQL 所做的,而且速度很快。
【问题讨论】:
-
在我的脑海中,我会说磁盘版本由于磁盘缓存而人为地快速。例如,请参阅here。编写好的基准很难。
-
我在 196 Gb RAM linux 上加载了近 10 GB 的数据,你认为操作系统缓存了大部分数据吗?
-
“通常,所有未直接分配给应用程序的物理内存都被操作系统用于page cache。”
-
Thx,我更新了我的问题更具体,Redis 访问数据实际上要快得多,但是因为我将数据存储为 JSON 字符串,所以解析部分真的很慢。我正在寻找一种直接在 python 对象中获取数据的方法,就像我们对 pyMySQL 所做的那样。
-
在字节流和内存中的 Python 对象之间总是有一个转换步骤。也就是说,众所周知,JSON 很慢,因此您可以随时尝试 msgpack 甚至 pickle。
标签: python database performance redis