gpt4 book ai didi

python - 在 while 循环中使用 python 的 core.Clock.GetTime() 方法 : timing distortions?

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:16 24 4
gpt4 key购买 nike

我在psychopy论坛上讨论计时精度时遇到了一个有趣的问题(psychopy是一个用python编写的心理学软件)。问题是这样的:

timer=core.Clock()#instantiate a clock
stimulus.draw()#draw stimulus
win.flip()#flip the monitor to make stimulus appear
Routine = True
While Routine:
key_press = event.getKeys(keyList=["f", "j"])#check keyboard's buffer
if len(key_press) > 0:#keypress detected!
RT = timer.getTime()#record response time
Routine = False

有人告诉我,在 while 循环内调用 getTime() 可能很危险:“一个非常紧密的循环会占用所有 CPU 时间,阻塞其他进程,这些进程可能最终会闯入并夺取控制权而为了完成积压工作,完全打乱了你的时间安排。在每次迭代中,调用类似 time.sleep(0.001) 的东西来为其他进程留出时间。”我不明白为什么会这样。有人可以阐明这个编程问题吗?

最佳答案

我会根据 How would I stop a while loop after n amount of time? 中的讨论尝试回答。 ,特别是安东尼的评论:https://stackoverflow.com/a/44723559/8763097

while True: 循环往往会占用 CPU 进程,我认为这被称为:Busy Waiting

Busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available.

Busy-waiting itself can be made much less wasteful by using a delay function (e.g., sleep()) found in most operating systems. This puts a thread to sleep for a specified time, during which the thread will waste no CPU time. If the loop is checking something simple then it will spend most of its time asleep and will waste very little CPU time.

因此,您的 while 循环花费了大量时间一遍又一遍地检查 len(key_press) 的 if 语句值。添加 sleep() 例程将允许 While 循环暂停,从而可以执行其他进程。

这可能就是您报告时间函数不一致的原因 - 函数 .core.getTime()不是核心 python 函数。它是你的心理包核心的一部分,它看起来不像一个进程时钟……它看起来像一个基本的时钟定时器。因此,计时器可能会受到 While 循环的 CPU 占用的影响。然而,在不了解更多有关程序包时钟处理的信息的情况下,这只是一个猜测。

也许为了避免此问题,请考虑将 time.perf_counter() 与 sleep 函数一起使用,因为这将包括计数内的任何 sleep() 时间。

编辑 1:也许一种解决方案是使用 MS VC++ 运行时库,该库包含在 Python 的核心中。

import msvcrt
import time

print("GO")
start = time.perf_counter()
while True:
if msvcrt.kbhit():
end = time.perf_counter()
print(end-start)
break

库应该能够处理命令以等待键盘按下,然后再进入循环中的下一步。它能解决问题吗?不完全的。问题真的能解决吗?我不确定...

关于python - 在 while 循环中使用 python 的 core.Clock.GetTime() 方法 : timing distortions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com