Search Unity

is mathf super slow?

Discussion in 'Scripting' started by laurentlavigne, Oct 22, 2021.

  1. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    6,331
    I see 400 floortoint taking up 0.07ms on a 8400, seems like a lot.
    Is there a fast mathf replacement lib somewhere on the webz?
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    356
    Mathf is using usual C# System.Math under the hood, so you should ask if C# standard Math is slow, but I doubt it is.
    It depends on what you compare it to.
    But if you really need to do big calculations fast, you can look at Unity Job System or self written multithreaded solution, I don't know what else to suggest.
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,992
    0.07ms for 400 FloorToInt you think is slow? Can we see your test case? Are you actually sure that the time is only the floortoint or are any other things involved? No memory access? 0.07ms/400 ==> about 5.7 million calls per second. FloorToInt is literally defined like this:
    Code (CSharp):
    1. public static int FloorToInt(float f)
    2. {
    3.     return (int)System.Math.Floor(f);
    4. }
    Where and how did you carry out your tests? inside the editor or in a build? If you did test in a build, what backend, what platform? If you test inside the editor you usually don't much optimisation like inlining. For example the rescaling algorithm I've posted over here is 8 times slower than the manually inlined version I posted on my dropbox. Though that was actually tested inside the editor.

    So chances are high that you're wasting performance on other things like method calls, memory access, etc. I highly doubt that the actual floor call and the int cast should be that slow. Though It should be clear that those are not atomic opcodes either, so the whole Mathf.FloorToInt call of course would take a few cycles.

    You may want to share your test code and how you actually measured the performance? 400 calls are not really enough to do any reasonable measureing if that's all you do.
     
    Lekret likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459