aardvark-platform / aardvark.base

Aardvark.Base is the foundation of the open-source Aardvark Platform for visual computing, real-time graphics, and visualization.
https://aardvarkians.com/
Apache License 2.0
153 stars 9 forks source link

Inlining of Col.** Funcs #71

Closed luithefirst closed 2 years ago

luithefirst commented 2 years ago

In our color types, we excessively use static functions to do conversion operations, such as FloatFromByte, ByteFromFloat or ByteFromFloatClamped. Inlining them would have nice potential for optimization. Calling the static functions directly and adding the AggressiveInlining attribute might already be sufficient, or maybe this can also be somehow implemented in the code generator.

Here is a quick benchmark I've created:

[SimpleJob(RuntimeMoniker.Net48)]
public class ColFunc
{
    C3b[] _cols;

    [GlobalSetup]
    public void Init()
    {
        var rnd = new RandomSystem(0);
        _cols = new C3b[1000].SetByIndex(i => rnd.UniformC3f().ToC3b());
    }

    [Benchmark]
    public C3f ToC3fFunc()
    {
        C3f sum = C3f.Black;
        foreach (var x in _cols)
            sum += x.ToC3f();
        return sum;
    }

    private const float c_byteToFloat = 1.0f / 255.0f;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public C3f ToC3fInline(C3b c)
    {
        return new C3f(
            c_byteToFloat * (float)c.R,
            c_byteToFloat * (float)c.G,
            c_byteToFloat * (float)c.B);
    }

    [Benchmark]
    public C3f ToC3fInline()
    {
        C3f sum = C3f.Black;
        foreach (var x in _cols)
            sum += ToC3fInline(x);
        return sum;
    }
}
Method Mean Error StdDev Code Size
ToC3fFunc 8.868 μs 0.1751 μs 0.3497 μs -
ToC3fInline 1.767 μs 0.0340 μs 0.0318 μs -