Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Best way min/max for burst compiler

Discussion in 'Burst' started by Alex1337rus, Mar 26, 2021.

  1. Alex1337rus

    Alex1337rus

    Joined:
    Mar 30, 2016
    Posts:
    37
    What is the best way to write this function for burst compile? (for best performance)
    Code (CSharp):
    1.      
    2. private bool Check(float3 t1, float3 t2)
    3. {
    4.   float3 tMin = min(t1, t2);
    5.   float3 tMax = max(t1, t2);
    6.  
    7.   return max(tMin.x, max(tMin.y, tMin.z)) <= min(tMax.x, min(tMax.y, tMax.z));
    8. }
    9.  
    I can manually inline tMin and tMax, replace min/max with ternary operator but will i have any profit with it?
     
  2. R2-RT

    R2-RT

    Joined:
    May 8, 2019
    Posts:
    38
    There are `math.cmin` and `math.cmax` which would simplify your return statement down to
    return math.cmax(tMin) <= math.cmin(tMax);


    I recommend playing around with Burst Inspector to determine which implementation has shorter assembly. It will likely be the fastest one.

    Just make function static and add [BurstCompile] attribute to its class and to function declaration.
     
    Yury-Habets likes this.
  3. Yury-Habets

    Yury-Habets

    Unity Technologies

    Joined:
    Nov 18, 2013
    Posts:
    1,167
    @R2-RT is correct - check the assembly.
    Inlining or doing tricks on C# side is unlikely to help, but you could always give it a try. :)
     
  4. Alex1337rus

    Alex1337rus

    Joined:
    Mar 30, 2016
    Posts:
    37
    Thanks! I will try
     
  5. Dinamytes

    Dinamytes

    Joined:
    Nov 3, 2016
    Posts:
    51
    I find it strange how you knew about inlining and not the math class, check out burst manual for optimization guidelines.