【问题标题】:How much CPU should a Python time.sleep(n) call usePython time.sleep(n) 调用应该使用多少 CPU
【发布时间】:2013-08-01 13:22:32
【问题描述】:

我有一个在旧笔记本电脑上运行的程序,它会不断监控 Dropbox 文件夹中是否添加了新文件。当它运行时,Python 进程在双核机器上使用了接近 50% 的 CPU,在 8 核机器上使用了大约 12%,这表明它使用了接近 100% 的一个核心)。这会散发出很多热量。

相关的代码是:

while True:
    files = dict ([(f, None) for f in os.listdir(path_to_watch)])
    if len(files) > 0:
        print "You have %s new file/s!" % len(files)
        time.sleep(20)

在没有新文件的情况下,当然大部分时间应该花在time.sleep() 等待上,我不会认为这会占用大量 CPU - 而the answers here 似乎说它应该'不会的。

那么两个问题:

1) 既然time.sleep() 不应该如此占用 CPU,那么这里发生了什么?

2) 是否有另一种方法可以监控文件夹的更改,从而降低运行速度?

【问题讨论】:

  • 你的time.sleep 缩进太远,把它放在while True 主块中,这样可以确保它一直运行。

标签: python time sleep


【解决方案1】:

1) 只有在有新文件时才会调用 sleep。

这样应该会好很多:

while True:
    files = dict ([(f, None) for f in os.listdir(path_to_watch)])
    if len(files) > 0:
        print "You have %s new file/s!" % len(files)
    time.sleep(20)

2) 是的,尤其是在使用 linux 时。 Gamin 会是我建议研究的东西。

例子:

import gamin
import time
mydir = /path/to/watch
def callback(path, event):
    global mydir
    try:
        if event == gamin.GAMCreated:
            print "New file detected: %s" % (path)
            fullname = mydir + "/" + path
            print "Goint to read",fullname
            data = open(fullname).read()
            print "Going to upload",fullname
            rez = upload_file(data,path)
            print "Response from uploading was",rez
    except Exception,e: #Not good practice
        print e
        import pdb
        pdb.set_trace()


mon = gamin.WatchMonitor()
mon.watch_directory(mydir, callback)
time.sleep(1)
while True:
    ret = mon.handle_one_event()
mon.stop_watch(mydir)
del mon

【讨论】:

  • 哇,缩进问题上的一记耳光!我会看看gamin,虽然我目前使用的是 Windows。
  • 我 99% 确定通过 Windows API 有一个 Windows 等价物,尽管您可能需要使用 IronPython。另一方面,我在发布后意识到,对 gamin 等的真正好处是您基本上可以获得即时更新;如果您主要关心的只是让 CPU 不会烧毁,那么您的睡眠轮询模式更有意义,只是保持简单。 (而且我们都被打过头了,虽然从理论上讲,python 应该更容易发现......我仍然记得一个 C 程序,我有一个悬挂的 else 看起来很好的缩进)
  • 问题是我发布的部分实际上是正确的。它让新文件有机会在 Dropbox 上同步。 real time.sleep() 更靠后,并不(很)容易被发现,但仍然缩进不正确。
【解决方案2】:

还有一个用于监控文件系统变化的跨平台API:Watchdog

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多