Redis性能提升

普通使用

# 定义普通函数
def func():
    """ 以普通方式 操作redis数据库"""
    conn = redis.Redis(host="192.168.0.113", port=6379, db=0, decode_responses=True) #

    # 逐个写入
    conn.set("name1", "jack")
    conn.set("age", 23)
    conn.lpush("friends", "lucy", "lili", "jingtian")
    conn.hset("children", mapping={"name": "zhsan"})

    conn.close()

优化使用

# 定义优化函数
def optimize_func():
    """ 优化后的操作 """
    # 使用连接池 创建连接,避免每次连接的创建、销毁
    conn = Redis(connection_pool=pool, db=0, decode_responses=True)

    # 使用管道 一次性执行命令  (事务>multi开启事务    >exec执行事务   >discard取消事务)
    pipe = conn.pipeline()
    pipe.set("name1", "tom")
    pipe.set("age", 33)
    pipe.lpush("friends", "jeken", "lili", "jingtian")
    pipe.hset("children", mapping={"age": 33})

    # 一次性执行
    pipe.execute()

    pipe.close()
    conn.close()

性能测试

# 性能测试

if __name__ == '__main__':
    timer1 = Timer("func()", "from __main__ import func")
    timer2 = Timer("optimize_func()", "from __main__ import optimize_func")

    # 重复测试五次,每次执行1000次
    r1 = timer1.repeat(5, number=1000)
    r2 = timer2.repeat(5, number=1000)

    print("普通:", r1)
    print("优化:", r2)

普通: [2.7437639, 2.6916931, 2.6703169000000004, 2.674367199999999, 2.7256414999999983]
优化: [0.5129146000000002, 0.5099906000000001, 0.4980922000000003, 0.5055642999999996, 0.5070465000000013]

性能优化约80%
 
 
 
下一篇: Redis发布订阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值