You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Performance issues for Math.Min, Math.Max for double/float #33057
Using Math.Min in a loop is almost 4 times slower than before.
General
Porting our libraries to .net core 3.1, we realized performance issues on Math.Min. Min is including in a loop with millions of iterations. The loop execution was almost 4 times slower than before.
I looked at the source code and realized that the AggressiveInlining option (MethImplAttribute) was missing on Math.Min and Max for floating point arguments.
Of course the function has changed to be compliant with the new IEEE standard, but I guess it still can be inlined.
As thought:
If we know from the use case that neither first nor seconds argument will be NaN there could be a "fast" version that emits minsd (on x86) for full speed (method M0 should emit minsd ideally).
The JIT can be tricked into this by using hw-intrinsics, but should do this by itself.
For compliance with IEEE 754:2019 we have Math.Min.
The asm isn't quite as bad when you look at the x64 version.
The main bloat comes from the IsNaN check which was cleaned up back in October and should be much smaller in .NET 5 (which sharplab doesn't support right now)
If we know from the use case that neither first nor seconds argument will be NaN there could be a "fast" version that emits minsd (on x86) for full speed (method M0 should emit minsd ideally).
This isn't a valid transformation because minsd doesn't correctly handle 0.0 vs -0.0, it always returns the second operand when IEEE 754 requires it return -0.0.
I had previously implemented a branchless version of this code which uses intrinsics, but the results weren't consistent on all platforms: dotnet/coreclr#22965 (this was also a version which didn't propagate NaN, so it would need to be tweaked slightly).
We might also be able to gain some perf by ensuring the non Zero/non NaN case is the "predicted" path if the former isn't viable.
Thank you for this change. I’m sure it will help.
I see this class has a IsNaN implementation. I‘m not sure if its implementation, which differs from double.IsNan. The only benefits I see is inlining. But to me Math.IsNan(double.NaN) is unsure.
Le 9 mars 2020 à 19:15, Günther Foidl ***@***.***> a écrit :
In ***@***.*** I added more tests for the edge cases.
Tested variants are here:
default (current master)
variant from #33057 (comment)
a version based on dotnet/coreclr#22965
All three passes the tests (on intel-x64).
Benchmark results (win-x64) and generated asm (linux-x64) are in this folder.
The raytracer -- as mentioned in #12159 -- is hacked together and gives on my machine (Intel x64) the following numbers:
Default: 48021 ms
InlinedOptimized: 38675 ms
Vectorized: 47637 ms
(Quite interesting that the branchless vectorized version doesn't perform better (on my machine) -- I didn't investigate why...maybe later)
Unfortunately I don't have access to other cpu-platforms (amd, arm) to run tests on.
Are there any other real-world benchmarks we can run for min/max?
So based on these numbers, I would go with InlinedOptimized variant.
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or unsubscribe.
Notably, there are a few places where codegen could be improved; but inlining and reordering things to assume inputs aren't the same or NaN provides the easiest win.
I see the following. Part of the differnce in numbers is due to the inputs given, as such I've run the benchmark with 4 different input variations and listed them below.
From the numbers, you can see that MinVectorized is fairly stable regardless of what inputs are given and other algorithms really start shining when the branch predictor can start working but may perform worse when it can't.
I poured the numbers in a chart (without case MathMin, as it's the worst):
For Ryzen MinReorderWithMinScalar performs best and is quite stable on the inputs.
For Intel MinReorder performs best.
So which one should we pick?
Do you know why minsd seems to be quite slower on Intel or how this can be circumvented?
other algorithms really start shining when the branch predictor can start working but may perform worse when it can't
This is what I would expect, but the figure looks partially somewhat different. The more "random" the inputs, the less time it takes. This feels a bit strange to me.
This is what I would expect, but the figure looks partially somewhat different. The more "random" the inputs, the less time it takes. This feels a bit strange to me.
It might have to do with internal mechanics of how the branch predictor works. It could also be a side effect of the test or some other factor.
Math.Min and Math.Max are really small functions, so we can't accurately test them using just a benchmark that calls them. This is because they take less time than the resolution of the high frequency timer on the system (which is sub 1 microsecond, but generally no more accurate than 100ns. Instead, we have to scale the number of operations done during the test, which can skew results.
We need something that isn't MinReorderWithMinScalar or MinVectorized as the software fallback in either case, and so we should just pick one that is the best overall, on average. We can then optimize other cases as needed.
I imagine all of these algorithms (minus MinVectorized) may behave differently depending on the surrounding code due to the number of branches/return statements they have.
Activity
stephentoub commentedon Mar 2, 2020
cc: @tannergooding
tannergooding commentedon Mar 2, 2020
Marked as up-for-grabs as it should be a trivial fix.
tannergooding commentedon Mar 2, 2020
We should also add tests covering
Min/Maxto dotnet/performance. @adamsitnik might be able to help with this side of things.Our existing math tests are here: https://github.com/dotnet/performance/tree/master/src/benchmarks/micro/runtime/Math/Functions
gfoidl commentedon Mar 3, 2020
Math.Min(double, double)produces quite a lot of asm (see methodsM1andM2. Do we really want to force the inline?As thought:
If we know from the use case that neither
firstnorsecondsargument will beNaNthere could be a "fast" version that emitsminsd(on x86) for full speed (methodM0should emitminsdideally).The JIT can be tricked into this by using hw-intrinsics, but should do this by itself.
For compliance with IEEE 754:2019 we have
Math.Min.I'll open a PR over there.
tannergooding commentedon Mar 3, 2020
The asm isn't quite as bad when you look at the x64 version.
The main bloat comes from the
IsNaNcheck which was cleaned up back in October and should be much smaller in .NET 5 (which sharplab doesn't support right now)tannergooding commentedon Mar 3, 2020
This isn't a valid transformation because
minsddoesn't correctly handle0.0vs-0.0, it always returns the second operand when IEEE 754 requires it return-0.0.tannergooding commentedon Mar 3, 2020
I had previously implemented a branchless version of this code which uses intrinsics, but the results weren't consistent on all platforms: dotnet/coreclr#22965 (this was also a version which didn't propagate NaN, so it would need to be tweaked slightly).
We might also be able to gain some perf by ensuring the non Zero/non NaN case is the "predicted" path if the former isn't viable.
4 remaining items
gfoidl commentedon Mar 5, 2020
gfoidl commentedon Mar 9, 2020
@tannergooding side question: should the workaround for BitConverter double <-> long be handled separate? (Cf. #12733 (comment)).
I would do so, to keep the changes focused...
gfoidl commentedon Mar 9, 2020
In gfoidl@b2fe76d I added more tests for the edge cases.
Tested variants are here:
All three passes the tests (on intel-x64).
Benchmark results (win-x64) and generated asm (linux-x64) are in this folder.
The raytracer -- as mentioned in #12159 -- is hacked together and gives on my machine (Intel x64) the following numbers:
(Quite interesting that the branchless vectorized version doesn't perform better (on my machine) -- I didn't investigate why...maybe later)
Unfortunately I don't have access to other cpu-platforms (amd, arm) to run tests on.
Are there any other real-world benchmarks we can run for min/max?
So based on these numbers, I would go with InlinedOptimized variant.
polijp commentedon Mar 10, 2020
gfoidl commentedon Mar 10, 2020
It's just copied over from
double.IsNaNalong other methods for easier tweaking of the code.tannergooding commentedon Mar 10, 2020
Yes, it should be a separate PR with its own jit-diff and potentially perf data.
tannergooding commentedon Mar 10, 2020
Thanks @gfoidl, I'm going to run some numbers on my AMD and Intel boxes in a bit and will share back as well.
tannergooding commentedon Mar 10, 2020
Variants tested and disassembly: https://gist.github.com/tannergooding/d81a6cd7530ec1cdc27e08530922f02a
Notably, there are a few places where codegen could be improved; but inlining and reordering things to assume inputs aren't the same or NaN provides the easiest win.
Ryzen 3900X
Ryzen 1800X
i7-7700
EgorBo commentedon Mar 11, 2020
That's why we need a
Fast Mathmode :-) to be able to just use a single instruction (e.g.minsd) and don't care about nans, etc 🙂Some dotnet/perf benchmarks are up to 3x faster with Fast-Math mode on Mono-LLVM (e.g. the Burgers ones)
gfoidl commentedon Mar 11, 2020
@tannergooding I updated my benchmarks with your variants -> results.
MinReorderWithMinScalarMinReorderWithMinScalar, but with the special cases split to a non-inlineable methodAll variants use optimized BitConverter.
From these numbers (for
double) InlinedOptimized is still the fasted variant (for my benchmarks).For the raytracer I get the following numbers (
float):For AMD it seems that
MinScalarhas much greater positive effect than on Intel.Can you run your benchmarks with
InlinedOptimized-variant as well, please?tannergooding commentedon Mar 11, 2020
I see the following. Part of the differnce in numbers is due to the inputs given, as such I've run the benchmark with 4 different input variations and listed them below.
From the numbers, you can see that
MinVectorizedis fairly stable regardless of what inputs are given and other algorithms really start shining when the branch predictor can start working but may perform worse when it can't.All inputs: val1 < val2
Ryzen 3900X
i7-7700
1/2 Inputs: val1 < val2; 1/2 Inputs: val2 < val1
Ryzen 3900X
i7-7700
1/3 Inputs: val1 < val2; 1/3 Inputs: val2 < val1; 1/3 Inputs: NaN
Ryzen 3900X
i7-7700
1/4 Inputs: val1 < val2; 1/4 Inputs: val2 < val1; 1/4 Inputs: NaN; 1/4 Inputs: val1 == val2
Ryzen 3900X
i7-7700
gfoidl commentedon Mar 13, 2020
I poured the numbers in a chart (without case

MathMin, as it's the worst):For Ryzen
MinReorderWithMinScalarperforms best and is quite stable on the inputs.For Intel
MinReorderperforms best.So which one should we pick?
Do you know why
minsdseems to be quite slower on Intel or how this can be circumvented?This is what I would expect, but the figure looks partially somewhat different. The more "random" the inputs, the less time it takes. This feels a bit strange to me.
tannergooding commentedon Mar 13, 2020
Looking at https://www.agner.org/optimize/instruction_tables.pdf, Skylake has a 4 cycle latency while Ryzen only has a 1 cycle latency (for
minss/minsdandmaxss/maxsd).It might have to do with internal mechanics of how the branch predictor works. It could also be a side effect of the test or some other factor.
Math.MinandMath.Maxare really small functions, so we can't accurately test them using just a benchmark that calls them. This is because they take less time than the resolution of the high frequency timer on the system (which is sub 1 microsecond, but generally no more accurate than 100ns. Instead, we have to scale the number of operations done during the test, which can skew results.We need something that isn't
MinReorderWithMinScalarorMinVectorizedas the software fallback in either case, and so we should just pick one that is the best overall, on average. We can then optimize other cases as needed.I imagine all of these algorithms (minus
MinVectorized) may behave differently depending on the surrounding code due to the number of branches/return statements they have.