Optimising sine wave animation performance

Hi I have generated a sine wave animation from some of the p5 examples files and it is pretty much exactly how I would like it to animate. However I have noticed it does generate quite heavy processor usage. So I am generally looking for advice on how I can possibly optimise the code to be lighter and smoother on slower computers / devices?

Here is the code I am currently using:

function setup () {
	let size = min(windowWidth, windowHeight) * 0.96;
	size = floor(size);
	createCanvas(windowWidth, windowHeight);
	noiseSeed(random(50));
	frameRate(25); 
	noFill();
}

function windowResized () {
	let size = min(windowWidth, windowHeight);
	size = floor(size);
	resizeCanvas(windowWidth, windowHeight);
	noiseSeed(random(50));
	frameRate(25); 
	draw();
}

function draw () {
	clear();
	beginShape();

	const _o = millis() * 0.0005;
	const amount = 20;
	const ampl = ( 630 / ( windowHeight ) * 100 ) + 120;

	for(var k=0;k<amount;k++) {
		beginShape();
		const offset = (1 - k / amount) * 3;
		const detail = 5;
		for(var i=0;i<(width+detail);i+=detail) {
			let y = height * 0.5;
			y += Math.sin(i * 0.01 - _o + ( k / 50 ) + offset) * ampl;
			y += Math.sin(i * 0.005 - _o + 5 + offset + noise(  50  ) ) * ampl;
			vertex(i, y);
		}
		stroke(255, 255, 255, 100);
		endShape();
	}
}
1 Like

To start with, there are unmatched top level beginShape calls that can be dropped. Also, constants being defined inside draw or inner loops when they don’t change. Also, noise(50) is returning the same value every time – it can be made a constant, or better just dropped entirely as it has little effect on the output.

https://editor.p5js.org/jeremydouglass/sketches/I0DkFhJFK

However keep in mind that it is difficult to predict the real impact on performance without testing, as there is a lot of hidden optimization that already happens automatically. You greatest improvement might come from either making a single sin() call in your inner loop or precomputing tables. Also, dropping your detail (e.g. to 10) will have a big impact on larger screens.

1 Like