Inconsistent multiplication performance with floats

前端 未结 2 675
渐次进展
渐次进展 2021-02-05 16:46

While testing the performance of floats in .NET, I stumbled unto a weird case: for certain values, multiplication seems way slower than normal. Here is the test case:

         


        
2条回答
  •  忘了有多久
    2021-02-05 17:23

    I suspect this has something to do with denormal values (fp values smaller than ~ 1e-38) and the cost associated with processing them.

    If you test for denormal values and remove them, sanity is restored.

        static void float32Multiply(float param) {
            float n = 1000f;
            int zeroCount=0;
            for (int i = 0; i < 1000000; ++i) {
                n = n * param;
                if(n<1e-38)n=0;
            }
            // Write result to prevent the compiler from optimizing the entire method away
            Console.Write(n);
        }
    

提交回复
热议问题