println()**ing编辑:我用** nanoTime() 做了一些,发现 stepPins[pin].toggle() 花费了4226微秒。现在我需要找到一种更快的方法来切换引脚。
我正在制作一个程序来控制一个音乐软盘驱动器阵列。目前,我有一种方法,每10微秒运行一次,通过读取一个短的01001011格式( 1=tick软盘中有8个软盘)来标记所需的软盘。
由于某种原因,代码运行得太慢,导致音符频率过低。
下面是方法及其类:
public class Timer implements Runnable
{
@Override
public void run()
{
int i = Main.currentSteps.get(Main.time);
try
{
if (Main.time > Main.maxTime)
{
Main.executor.remove(Main.timer);
FloppyController.resetAll();
}
if ((i & 1) == 1)
{
FloppyController.stepPin(0);
}
if ((i & 2) == 2)
{
FloppyController.stepPin(1);
}
if ((i & 4) == 4)
{
FloppyController.stepPin(2);
}
if ((i & 8) == 8)
{
FloppyController.stepPin(3);
}
if ((i & 16) == 16)
{
FloppyController.stepPin(4);
}
if ((i & 32) == 32)
{
FloppyController.stepPin(5);
}
if ((i & 64) == 64)
{
FloppyController.stepPin(6);
}
if ((i & 128) == 128)
{
FloppyController.stepPin(7);
}
}
catch (Exception e) {}
Main.time++;
}
}至于它的价值,我的Main.java类的相关部分:
public class Main
{
public static ArrayList<Short> currentSteps;
public static ArrayList<Note> all = new ArrayList<Note>();
public static long maxTime = 0;
public static ScheduledThreadPoolExecutor executor;
public static Timer timer;
public static int time;
public static void main(String[] args) throws InterruptedException, InvalidMidiDataException, IOException, MidiUnavailableException
{
//initialize
FloppyController.init();
currentSteps = new ArrayList<Short>();
FloppyController.resetAll();
for (int o = 0; o < Math.ceil(maxTime / 10); o++)
{
currentSteps.add((short) 0);
}
//populate list
for (Note n : all)
{
for (int a = Math.round(n.timeStart / 10); a <= Math.round(n.timeEnd / 10); a += n.wait)
{
currentSteps.set(a, (short) (currentSteps.get(a) + (((currentSteps.get(a) & (short) Math.pow(2, n.channel)) == Math.pow(2, n.channel)) ? 0 : Math.pow(2, n.channel))));
}
}
//start play executions
executor = new ScheduledThreadPoolExecutor(1);
long resolution = 10; //# of microsecond iterations
timer = new Timer();
executor.scheduleAtFixedRate(timer, 0, resolution, TimeUnit.MICROSECONDS);
}如何优化run()的Timer.class方法
我还考虑将currentSteps ArrayList更改为HashMap,并且只包括非零值,并将其对应的时间作为关键,因为我在Raspberry Pi上遇到内存问题。
下面是stepPin方法:
public static void stepPin(int pin) throws InterruptedException
{
if (pinPositions[pin] >= 79)
{
changeDirection(pin, true);
}
else if(pinPositions[pin] < 0)
{
changeDirection(pin, false);
}
stepPins[pin].toggle();
stepPins[pin].toggle();
pinPositions[pin] += pinDirections[pin].isLow() ? 1 : -1;
}发布于 2016-01-12 09:59:04
我建议每个软盘驱动器启动一个线程,并使用两个字节数组作为缓冲区(让我们称它们为"A“和"B")来调度声音。缓冲器应该足够大,足以播放几秒钟的音乐。伪码是这样的:
假设stepPin阻塞,但只阻塞它的线程,这将使您的线程与这些延迟隔离开来。
https://stackoverflow.com/questions/34739202
复制相似问题