使python代码运行得更快以减少错误

2024-09-30 16:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用python进行一个项目。我的目标是能够作出一个积极的噪音消除设备使用树莓圆周率。 现在,我已经写了这个程序,它开始录下我想要取消的声音,然后用PID控制器计算出一个与原来的相反的波形,然后播放它,以便取消它。你知道吗

我现在的问题是,这个程序需要一些时间来计算,所以一旦它计算出了反向波,原来的一个已经通过了设备,我得到了大约0.02秒的偏移量。我的目标是尽可能减少这种偏移,然后通过增加麦克风和扬声器之间的距离来补偿它。现在,偏移量是0.02秒,声速是340米/秒,我必须把这个距离设为6.8米(0.02*340=6.8),这太多了。你知道吗

那么我怎样才能让程序运行得更快呢? 代码如下:

import pyaudio, math, struct
import numpy as np
import matplotlib.pyplot as plt

#INITIAL CONFIG

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = float(input('Seconds: '))

p = pyaudio.PyAudio()
guess = 0
integral = 0
kp = 0.5
ki = 200
kd = 9999
dt = RATE**(-1)
ddt = RATE
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=chunk)

total_error = 0
previous_e = 0

#Start processing
print ("* recording")

for i in range(0, int(RATE / chunk * RECORD_SECONDS)):
    byted = (b'')
    for element in np.fromstring(stream.read(chunk), 'Int16'):
        error = -(guess - element)
        integral += error*dt
        derivative = (error - previous_e) / ddt
        guess += int(round(kp*error + ki*integral + kd*derivative, 0))
        byted += struct.pack('<h', -guess)
        previous_e = error
    stream.write(byted, chunk)

#Close
stream.stop_stream()
stream.close()
p.terminate()

input ('Press enter to exit...')

请注意:不要只回答一个解决方案,请解释为什么它提高了程序的速度,因为我不仅希望这个工作,而且我也想学习。你知道吗

谢谢


Tags: import程序距离目标inputstreamrateerror
1条回答
网友
1楼 · 发布于 2024-09-30 16:24:59

我的粗略模拟表明,通过不在循环中串联字节字符串,而是在数组中收集它们并在循环后连接它们,您可能会获得一些速度:

byted_array = []
    for element in np.fromstring(stream.read(chunk), 'Int16'):
        ...
        byted_array.append(struct.pack('<h', -guess))
        ...
    stream.write(b''.join(byted_array), chunk)

相关问题 更多 >