[英]Python: Improving performance - Writing to database in seperate thread
[英]Writing data to disc in seperate thread (in parallel)
我想在一個循環中多次啟動 function,每次從相機獲取圖像並將圖像寫入光盤,而無需循環等待此過程完成。 所以每次調用這個 function 時,它都會與啟動 function 的循環並行運行,這樣我就可以同時繼續做其他時間敏感的事情。
我已經制作了這個示例,它使 function 的第一次“執行”與循環並行運行,然后第二次失敗,因為我 can't.start() 它兩次。 這可以通過其他方式實現嗎?
示例(原始帖子 - 更新如下)
import numpy as np
import threading
import time
def imacq():
print('acquiring image...')
time.sleep(1.8)
print('saved image...')
return
# Start image acqusition and writing to disc thread
imacq_thread = threading.Thread(target=imacq)
starttime = time.time()
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 5
running = True
flag = True
for cycles in range(1,20):
print(cycles)
if cycles%image_cycles == 0:
if flag is True:
imacq_thread.start() # this works well the first time as intended
# imacq() # this does not work as everything is paused until imacp() returns
flag = False
else:
flag = True
time.sleep(0.4)
編輯:在得到 Sylvaus 的反饋后:我制作了兩個不同的版本來觸發 function,最終將用於在驅動器上獲取和存儲圖像,並與決定發送觸發器/執行 function 的時間的主腳本並行。 一個版本基於 Sylvaus 的答案(線程),另一個版本基於多處理。
基於 Sylvaus 的回答(線程)的示例:
import matplotlib.pyplot as plt
import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor
def imacq():
print('taking image')
n = 10000
np.ones((n, n))*np.ones((n, n)) # calculations taking time
print('saving image')
return
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 20
max_cycles = 100
freq = 10
cycles = 1
sigSign = 1
running = True
flag = True
timeinc = []
tic = time.time()
tic2 = tic
timeinc = np.zeros(max_cycles)
starttime = time.time()
with ThreadPoolExecutor() as executor:
while running:
t = time.time()-starttime
tim_arr[:-1] = tim_arr[1:]
tim_arr[-1] = t
signal = np.sin(freq*t*(2.0*np.pi))
sig_arr[:-1] = sig_arr[1:]
sig_arr[-1] = signal
time.sleep(0.00001)
# Calculate cycle number
sigSignOld = sigSign
sigSign = np.sign(sig_arr[-1]-sig_arr[-2])
if sigSign == 1 and sigSignOld != sigSign:
timeinc[cycles] = time.time()-tic
cycles += 1
print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
tic = time.time()
if cycles%image_cycles == 0:
if flag is True:
# The function is submitted and will be processed by a
# a thread as soon as one is available
executor.submit(imacq)
flag = False
else:
flag = True
if cycles >= max_cycles:
running = False
print('total time: ', time.time()-tic2)
fig = plt.figure()
ax = plt.axes()
plt.plot(timeinc)
基於多處理的示例:
import matplotlib.pyplot as plt
import numpy as np
import time
from multiprocessing import Process, Value, Lock
def trig_resp(running, trigger, p_count, pt, lock):
while running.value == 1: # note ".value" on each sharedctype variable
time.sleep(0.0001) # sleeping in order not to load CPU too excessively
if trigger.value == 1:
with lock: # lock "global" variable before wrtting to it
trigger.value = 0 # reset trigger
tic = time.time()
# Do a calculation that takes a significant time
n = 10000; np.ones((n, n))*np.ones((n, n))
with lock:
pt.value = time.time() - tic # calculate process time
p_count.value += 1 # count number of finished processes
return
if __name__ == "__main__":
# initialize shared values (global accross processes/sharedctype).
# Type 'i': integer, type 'd': double.
trigger = Value('i', 0) # used to trigger execution placed in trig_resp()
running = Value('i', 1) # A way to break the loop in trig_resp()
p_count = Value('i', 0) # process counter and flag that process is done
pt = Value('d', 0.0) # process time of latest finished process
lock = Lock() # lock object used to avoid raise conditions when changing "global" values.
p_count_old = p_count.value
p1 = Process(target=trig_resp, args=(running, trigger, p_count, pt, lock))
p1.start() # Start process
# A "simulated" sinusiodal signal
array_len = 50
sig_arr = np.zeros(array_len) # Signal array
tim_arr = np.zeros(array_len) # Correpsonding time array
freq = 10 # frequency of signal
# trigger settings
im_int = 20 # cycle interval for triggering (acquiring images)
max_cycles = 100 # max number of cycles before stopping main
# initializing counters etc.
cycles = 1 # number of cycles counted
sigSign = 1 # sign of signal gradient
flag = 1 # used to only set trigger once for the current cycle count
trigger_count = 0 # counts how many times a trigger has been set
tic = time.time()
tic2 = tic
timeinc = np.zeros(max_cycles) # Array to keep track of time used for each main loop run
starttime = time.time()
while running.value == 1:
time.sleep(0.00001) # mimics sample time (real world signal)
t = time.time()-starttime # local time
signal = np.sin(freq*t*(2.0*np.pi)) # simulated signal
# Keeping the latest array_len values (FIFO) of t and signal.
tim_arr[:-1] = tim_arr[1:]
tim_arr[-1] = t
sig_arr[:-1] = sig_arr[1:]
sig_arr[-1] = signal
if p_count.value == p_count_old + 1: # process have finished
print('Process counter: ', p_count.value, 'process_time: ', pt.value)
p_count_old = p_count.value
# Calculate cycle number by monotoring sign of the gradient
sigSignOld = sigSign # Keeping track of previous signal gradient sign
sigSign = np.sign(sig_arr[-1]-sig_arr[-2]) # current gradient sign
if sigSign == 1 and sigSignOld == -1: # a local minimum just happened
timeinc[cycles] = time.time()-tic
cycles += 1
print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
tic = time.time()
flag = 1
if cycles % im_int == 0 and flag == 1:
if cycles > 0:
if trigger_count > p_count.value:
print('WARNING: Process: ', p_count.value,
'did not finish yet. Reduce freq or increase im_int')
trigger.value = 1
trigger_count += 1
print('Trigger number: ', trigger_count)
flag = 0
if cycles >= max_cycles:
running.value = 0
print('total cycle time: ', time.time()-tic2)
# Print the process time of the last run
if p_count.value < max_cycles//im_int:
if p_count.value == p_count_old + 1:
print('process counter: ', p_count.value, 'process_time: ', pt.value)
p_count_old = p_count.value
print('total process time: ', time.time()-tic2)
fig = plt.figure()
ax = plt.axes()
plt.plot(timeinc)
我使用的是 windows 10 筆記本電腦,因此時間(主while循環“運行時...:”的每個循環中的時間增量)取決於我的計算機上發生的其他事情,但基於多處理的版本似乎不太敏感這比基於線程的。 然而,基於多處理的解決方案不是很優雅,我懷疑可能有一個更智能的解決方案(更簡單,更不容易出錯),它可以實現相同或更好的效果(一致的時間增量和較低的 CPU 負載)。
非常感謝有關改進這兩種解決方案的任何反饋。
您可以使用Executor 。這樣,您可以簡單地提交您的任務,它們將根據您使用的 Executor 類型進行處理。
我不知道您的imacq
中有什么,因此您可能需要嘗試ThreadPoolExecutor
和ProcessPoolExecutor
來找到最適合您的應用程序的一個。
例子:
import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor
def imacq():
print('acquiring image...')
time.sleep(1.8)
print('saved image...')
return
starttime = time.time()
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 5
running = True
flag = True
with ThreadPoolExecutor() as executor:
for cycles in range(1,20):
print(cycles)
if cycles%image_cycles == 0:
if flag is True:
# The function is submitted and will be processed by a
# a thread as soon as one is available
executor.submit(imacq)
flag = False
else:
flag = True
time.sleep(0.4)
您的采集設備、數據速率和容量的詳細信息似乎不是很清楚,但我的印象是,問題在於您希望盡可能快地采集一個信號,並希望捕獲圖像並將其寫入磁盤只要該信號“有趣”但不延遲信號的下一次采集,就盡快。
因此,在主信號采集過程和圖像捕獲過程之間似乎需要進行最少的數據交換。 恕我直言,這表明多處理(因此沒有 GIL)和使用隊列(沒有大量數據要腌制)在兩個進程之間進行通信。
所以,我會看這種類型的設置:
#!/usr/bin/env python3
from multiprocessing import Process, Queue, freeze_support
def ImageCapture(queue):
while True:
# Wait till told to capture image - message could contain event reference number
item = queue.get()
if item == -1:
break
# Capture image and save to disk
def main():
# Create queue to send image capture requests on
queue = Queue(8)
# Start image acquisition process
p = Process(target=ImageCapture, args=(queue,))
p.start()
# do forever
# acquire from DAQ
# if interesting
# queue.put(event reference number or filename)
# Stop image acquisition process
queue.put(-1)
p.join()
if __name__ == "__main__":
# Some Windows thing
freeze_support()
main()
如果ImageCapture()
進程跟不上,啟動兩個或更多。
在我的 Mac 上,我測量了 32 微秒隊列的平均消息傳遞時間,以及 100 萬條消息的最大延遲為 120 微秒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.