Python time.sleep(n)调用应使用多少CPU

时间:2013-08-01 13:22:33

标签: python time sleep

我有一个在旧笔记本电脑上运行的程序,该程序不断监视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)是否有另一种方法可以监控文件夹中是否存在更冷的变化?

2 个答案:

答案 0 :(得分:3)

1)只有在有新文件时才会调用您的睡眠。

这应该会好得多:

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

答案 1 :(得分:2)

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