I have this method:
public double sineWave(double t)
{
return amplitude==0?0:Math.sin(t * frequency * Math.PI*2 + phase) * amplitude;
}
It is called by another method in another class to generate a sample of a simple sine wave, which is then added in a buffer to send to the sound card. t is the time. For some reason, the more the application calls this method, the slower it gets. It just makes no sense, after 15 seconds it’s slow enough to use a full core of my CPU and make the audio stutter.
I’m 100% sure it’s this piece of code, because if I replace it with a return 0, the time it takes to run it (measured with System.nanotime()) is constant.
Why is this happening? Is there something I can do to fix this?
From the information here – while it is not clear how big your buffer is, you are incrementing t with each iteration. Assuming your frequency is quite high, you are increasing the Sin() argument with each iteration.
Have checks to see if the argument is constantly increasing to a very high value.
A quick and dirty test shows that Sin performance goes down –