繁体   English   中英

写入python日志的最快方法

[英]Fastest way to write to a log in python

我在uWSGI中使用gevent循环,然后写入redis队列。 我得到大约3.5 qps。 有时候,redis连接会出现问题......如果失败,那么写一个文件,我将有一个单独的进程稍后进行清理。 因为我的应用程序非常了解延迟,在python中转储到磁盘的最快方法是什么? python日志记录是否足够?

如果延迟是您的应用程序的关键因素,无限期写入磁盘可能会使事情变得非常糟糕。

如果你希望在redis仍处于运行状态时重启你的服务器,我认为没有其他解决方案而不是写入磁盘,否则你可能想尝试使用ramdisk。

你确定第二台带有第二个redis实例的服务器不是更好的选择吗?

关于日志记录,我只是使用低级I / O函数,因为它们的开销较小(即使我们谈论的机器周期很少)

附加到磁盘上的文件很快。

:~$ time echo "this happened" >> test.file

real    0m0.000s
user    0m0.000s
sys     0m0.000s

使用Python附加到文件似乎与bash大致相同。 日志记录模块似乎确实增加了一点开销:

import logging
import time

logging.basicConfig(filename='output_from_logging')
counter = 0

while counter < 3:
    start = time.time()
    with open('test_python_append', 'a') as f:
        f.write('something happened')
    counter += 1
    print 'file append took ', time.time() - start

counter = 0
while counter < 3:
    start = time.time()
    logging.warning('something happened')
    counter += 1
    print 'logging append took ', time.time() - start

这给了我们这个输出:

file append took  0.000263929367065
file append took  6.79492950439e-05
file append took  5.41210174561e-05
logging append took  0.000214815139771
logging append took  0.0001220703125
logging append took  0.00010085105896

但是在宏大的计划中,我怀疑这个操作将是代码库中非常昂贵的一部分,并且可能不值得担心。 如果您担心延迟,那么您应该编写代码python -m cProfile code_to_test.py 这将告诉您每个函数的使用时间以及应用程序花费时间的位置。 我严重怀疑它主要是记录错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM