我正在用 Python 创建一个实时跟踪日志文件的程序,我的代码如下:
import time
with open('/Users/alexandrelara/Library/Logs/Unity/Player.log') as f:
while True:
line = f.readline()
if line:
if line.startswith('[Zone]') and "tag=PLAYSTATE value=LOSING" in line:
print(line)
time.sleep(1)
continue
问题是 Python 进程使用了大约 100% 的 CPU,正如您在这张图片上看到的:
让线程休眠 1 秒没有帮助,高于该值的值不会给我想要的结果,因为它是一个游戏日志,每个操作都会在日志中产生很多行。
有什么办法可以提高CPU使用率吗?还是我不应该为此使用 Python?
请您参考如下方法:
尝试在 else block 上使用 sleep :
import time
with open('/Users/alexandrelara/Library/Logs/Unity/Player.log') as f:
while True:
line = f.readline()
if line:
if line.startswith('[Zone]') and "tag=PLAYSTATE value=LOSING" in line:
print(line)
else:
time.sleep(1)
