gpt4 book ai didi

python - 当其他应用程序正在运行时,线程运行速度不够快

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:54 26 4
gpt4 key购买 nike

我正在使用线程模块在后台运行一个函数,而我的脚本的其余部分正在执行。线程函数包含一个 for 循环,它等待外部 5 伏触发器,每 15 毫秒发生一次,然后继续下一个循环迭代。

当此代码是唯一在 PC 上运行的代码时,一切都按预期工作。然而,当我运行其他必要的应用程序时,对 cpu 造成压力,线程函数中的 For 循环仅在 15 毫秒的时间窗口内执行并继续进行下一次迭代,大约有 90% 的时间。

线程函数的输入是一个 ctypes 指针列表。

我在一个类中运行线程函数,因此使用多处理很棘手(我不确定这是否有帮助)。

我试图用这两个类的框架来说明下面的问题

import ctypes
import Write_transient_frames_func
import SendScriptCommands
from threading import Thread

class SlmInterface():

def __init__(self,sdk):

self.sdk = sdk

def precalculate_masks(self, mask_list):

'''takes input mask_list, a list of numpy arrays containing phase masks
outputs pointers to memory location of masks
'''

#list of pointers to locations of phase mask arrays in memory
mask_pointers = [mask.ctypes.data_as(POINTER(c_ubyte)) for mask in mask_list]

return mask_pointers

def load_precalculated_triggered(self, mask_pointers):

okay = True
print('Ready to trigger')

for arr in mask_pointers:

okay = self.Write_transient_frames_func(self.sdk, c_int(1), arr, c_bool(1), c_bool(1), c_uint(0))

assert okay, 'Failed to write frames to board'
print('completed trigger sequence')


class Experiment():

def run_experiment(self, sdk, mask_list):

slm = SlmInterface(sdk)

#list of ctypes pointers
mask_pointers = slm.precalculate_masks(mask_list)

##the threaded function
slm_thread = Thread(target=slm.load_precalculated_triggered, args = [mask_pointers])
slm_thread.start()

time.sleep(0.1)

# this function loads the 15ms trigger sequences to the hardware and begins the sequence
self.mp_output = SendScriptCommands()

是否可以加快线程函数的执行速度?并行处理有帮助吗?还是我从根本上受到了 CPU 的限制?

最佳答案

不幸的是,Python 可能无法做得更好。 Python 有一个 global interpreter lock ,这意味着多线程无法像在其他语言中那样工作。

关于python - 当其他应用程序正在运行时,线程运行速度不够快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764106/

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