2
\$\begingroup\$

Should I just use the built-in sin() function or my custom sine function?
I'm concerned about performance here. I don't care about accuracy much here because I use it to just get wave effects in my shader.

The shader is for mobile platforms (OpenGL ES)

Here's my code

float customSin(float x){
   x = fract( 0.75 + x*0.159155 )*2.0 - 1.0; 
   return x*x * (6.0 - 4.0*x) - 1.0;
}

Here's my algorithm

x is the input, y is the output

r = 0.75 + x/(π*2)
a = | r- floor(r) - 0.5 |*2
y = ( 3(a^2) - 2(a^3) )*2 - 1

I checked the graph, and it's pretty close to the actual sine.

Which one should I go with?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Did you measure the performance? \$\endgroup\$
    – Philipp
    Apr 25, 2021 at 11:31
  • 3
    \$\begingroup\$ I agree with the comment above, this sounds like a question you can answer for yourself with more certainty by profiling the impacts of the two options in the shaders you use. That will tell you not just which is faster, but which is faster in your specific use case — something a stranger would have a harder time determining. \$\endgroup\$
    – DMGregory
    Apr 25, 2021 at 11:36

1 Answer 1

6
\$\begingroup\$

ATI made an announcement that the sine / cosine instructions in their newest GPUs now requires only a single clock cycle... in 2004! Modern GPUs in fact have special function units specifically for calculating trigonometric functions.

So any hand-written sine or cosine function is unlikely to perform any better than the intrinsic sin() / cos() function, no matter how many accuracy concessions you make. They are just insanely optimized in hardware.

\$\endgroup\$
4
  • \$\begingroup\$ Wow! I didn't even know that was possible! I've still been trying to be a bit frugal with my trig use in shaders, but maybe that's outdated thinking. \$\endgroup\$
    – DMGregory
    Apr 25, 2021 at 12:02
  • \$\begingroup\$ So " 0.5-0.5*cos(x*3.14159265) " is faster than " x*x*(3.0-2.0*x) "? \$\endgroup\$
    – devendran
    Apr 25, 2021 at 12:56
  • \$\begingroup\$ @devendran your profiler could answer that for you more authoritatively. Usually it depends on context. Sometimes cores can overlap certain operations, depending on what else is going on in the shader. So the best way to know for sure what makes a particular shader run best is to try it and measure it. \$\endgroup\$
    – DMGregory
    Apr 27, 2021 at 0:09
  • \$\begingroup\$ @DMGregory Ok, I will check it in my shader. I'm kind of a newb to glsl shaders, thats why I asked. \$\endgroup\$
    – devendran
    Apr 27, 2021 at 8:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .