Repository navigation
Implement efficient/correct Comparer.get_Default and EqualityComparer.get_Default - #4935
Conversation
…parer.get_Default This work has several parts that largely hook up into the existing infrastructure in the class library we built for Project N. 1. Generate specialized method bodies for Comparer.Create and EqualityComparer.Create that create the right comparer specialized for the given T (if T implement the interface, doesn't implement the interface, is nullable, or is an enum) 2. If specialization is not possible at compile time, fall back to using template type loader to load the right type. 3. Add code that ensures appropriate templates get generated. This is a bit of a divergence from what Project N does because there we don't track precisely what we need and rely on universal shared code to fill in the blanks. 4. Enable RyuJIT optimization around EqualityComparer.get_Default that lets us devirtualize subsequent calls on the result of the intrinsic.
|
Contributes to #763. I won't say "fixes", because there's still this thing in Array.CoreRT.cs around Cc @dlewis-arcontech this might help with the perf in your benchmark. |
| throw new NotSupportedException(); | ||
| #else | ||
| // CORERT: TODO: https://github.com/dotnet/corert/issues/763 | ||
| return (_default = new DefaultEqualityComparer<T>()); |
There was a problem hiding this comment.
DefaultComparer/DefaultEqualityComparer can be deleted now (or moved under #if false if we want to keep it around for testing purposes).
There was a problem hiding this comment.
Ah yes. Ifdef'd out.
| TypeSystemContext context = type.Context; | ||
|
|
||
| if (context.IsCanonicalDefinitionType(type, CanonicalFormKind.Any) || | ||
| (type.IsRuntimeDeterminedSubtype && !type.HasInstantiation)) |
There was a problem hiding this comment.
So this will optimize the struct X<T> : IEquatable<T> case you have been worried about properly, correct?
There was a problem hiding this comment.
Yes. This method handles it, because it's shared with the logic that ensures templates are presents (and the devirtualization logic). But if T ends up being Canon, we reject generating a specialized method body for it in EmitComparerAndEqualityComparerCreateCommon and fall back to the type loader.
|
@MichalStrehovsky thanks for the code update and letting me know. I'm traveling at the moment but I'll be back at my pc on Friday, I'll rerun the tests then and post the results. |
|
Hello @MichalStrehovsky, I've rerun the tests and the commit has definitely improved the performance. Previously the results were:
After updating the results are:
If you'd like to me to analyze the differences any further please let me know. I also wanted to ask what are the hopes/aims for optimization with CoreRT, ultimately would you expect the generated code on average to be more performant than the JIT code? As you'd have longer to spend on the compile time optimization step I'd imagine this would be a goal. |
|
Yes, we would love to hear about where the bottlenecks are. There is no fundamental reason why CoreRT should be significantly slower than CoreCLR - the bottlenecks are bugs or not-yet-implemented features.
We do not have a cross-platform code generator today that is capable of doing significantly more optimizations than RyuJIT. There are a few limits that you can raise in RyuJIT around things like inlining heuristics, but it is unlikely to make a huge difference. We have experimented with LLVM in https://github.com/dotnet/llilc, but getting LLVM to produce better code on average than RyuJIT proved to be quite hard. We may come back to LLVM in future - it is not in our current plans though. |
|
@jkotas happy to help investigate. Not sure how to profile CoreRT on Linux but if you can point me in the right direction I can take a look. |
|
It maybe useful to collect some basic GC stats, e.g. add the following at the end of your benchmark: Console.WriteLine($"ServerGC: {System.Runtime.GCSettings.IsServerGC}");
Console.WriteLine($"TotalMemory: {GC.GetTotalMemory(false)}");
for (int i = GC.MaxGeneration; i >= 0; i--)
Console.WriteLine($"Gen{i}: {GC.CollectionCount(i)}");It will give us a quick read on whether or not the GC is behaving approximately the same between the two cases. For CoreRT, the general techniques and tools used to profile C/C++ programs should work on CoreRT. I would start with sampling CPU using perf (http://www.brendangregg.com/perf.html). For CoreCLR, it is harder to get symbols for JITed code. The helper script and instructions are at https://github.com/dotnet/coreclr/blob/master/Documentation/project-docs/linux-performance-tracing.md |
|
@jkotas thanks for the information, I've added the additional code you posted above and the results are: CoreCLR: ServerGC: False CoreRT: ServerGC: False I'll familiarize myself with the links you sent over on profiling, just let me know what to check next and I'll take a look. |
|
~1.4x more Gen0 GC's is something to look into a more. It suggest that there are more allocations in CoreRT than in CoreCLR. Does your benchmark use |
….get_Default (dotnet#4935) This work has several parts that largely hook up into the existing infrastructure in the class library we built for Project N. 1. Generate specialized method bodies for Comparer.Create and EqualityComparer.Create that create the right comparer specialized for the given T (if T implement the interface, doesn't implement the interface, is nullable, or is an enum) 2. If specialization is not possible at compile time, fall back to using template type loader to load the right type. 3. Add code that ensures appropriate templates get generated. This is a bit of a divergence from what Project N does because there we don't track precisely what we need and rely on universal shared code to fill in the blanks. 4. Enable RyuJIT optimization around EqualityComparer.get_Default that lets us devirtualize subsequent calls on the result of the intrinsic.
|
@jkotas no async methods or thread pools used in the benchmark. There are standard threads (just using new Thread) created at the start of the benchmark and they are used to dispatch events. I've had a look a the perf links you've sent and set up my machine with the necessary installers for CoreCLR, I haven't had a chance to run any performance tests yet but hopefully I'll get a chance today. Anything specific you'd like me to try out initially? |
|
I think that the ~1.4x more Gen0 GC's is something to drill into. Could you please collect data on how much is each thread in the benchmark allocating using Other than that, you can collect profiles on both CoreCLR and CoreRT and try to compare them side-by-side whether anything jumps out: go from the top and try to find where the most significant differences in inclusive time are. |
This is the remainder of dotnet#4935. We special case a couple methods on Array to avoid allocating a full EqualityComparer per each array type. This saves 22 kB on hello world (comparers for a bunch of primitive types and enums). Same as in dotnet#4935 - we restrict the optimization to non-shared value types. On Project N we would also optimize shared valuetypes, but these are rare enough that it's probably not worth building the infrastructure for. Fixes dotnet#763.
This is the remainder of dotnet#4935. We special case a couple methods on Array to avoid allocating a full EqualityComparer per each array type. This saves 22 kB on hello world (comparers for a bunch of primitive types and enums). Same as in dotnet#4935 - we restrict the optimization to non-shared value types. On Project N we would also optimize shared valuetypes, but these are rare enough that it's probably not worth building the infrastructure for. Fixes dotnet#763.
* Implement efficient Array.IndexOf This is the remainder of #4935. We special case a couple methods on Array to avoid allocating a full EqualityComparer per each array type. This saves 22 kB on hello world (comparers for a bunch of primitive types and enums). Same as in #4935 - we restrict the optimization to non-shared value types. On Project N we would also optimize shared valuetypes, but these are rare enough that it's probably not worth building the infrastructure for. Fixes #763.
|
@jkotas sorry for the slow response I've been a bit busy over the last few days. I've added code to write out GC.GetAllocatedBytesForCurrentThread but I'm getting a compile error, if I add: At the end of main it all compiles and runs fine, but for a thread if I have something like: Then at the end of process: I get the following compile error: WorkItemDispatcher/WorkItemDispatcher.cs(163,50): error CS0117: 'GC' does not contain a definition for 'GetAllocatedBytesForCurrentThread' Could you advise what I'm doing wrong here? Most other GC methods are available within the context of the thread but somehow it seems the GetAllocatedBytesForCurrentThread is not there. |
|
|
|
@MichalStrehovsky That's exactly it I'll change the project type of the assembly to .Net Core and post the results. Thanks! |
|
I increased threads the test slightly in the hope it'd expose the issue quicker, the results are: CoreRT: Thread (Chain Test) TestChain1 dataset TestDataset4 TotalMemory: 13466016 CoreCLR: Thread (Chain Test) TestChain1 dataset TestDataset1 TotalMemory: 14095496 What is interesting, I'll confirm this soon, but I believe in the test the Generic events dispatcher thread isn't used just created at the start and closed at the end and the same for Instrument Discovery dispatcher thread but they both seem to be the main difference. |
|
@MichalStrehovsky I've just confirmed the Generic events dispatcher and Instrument Discovery dispatcher, in this test case, just enter the thread entry point which enters a loop and then sits on a WaitHandle.WaitAny with an array of wait handles (process job work handle and exit wait handle). Gets the exit wait handle signaled and breaks out and exits the function without processing any work items. So doing very little. |
|
The dispatcher that is actually doing some work in this test 'Thread Work item dispatcher' is using a lot more memory too. This dispatchers kick off a long running back ground thread that sits on WaitAny waiting for a job to process or to exit. Then when you want to add a job to process you call an AddItem method with an Anonymous delegate of the work item to be processed, this is added to a queue and the workitem wait handle is signaled, the dispatching thread then Invokes the anonymous delegate and then once finished goes back around to the WaitAny until signaled again. So basically a way to dispatch decoupled workitems in order via a dispatching thread. I thought it was probably worth adding a more detailed description as it looks like this area could be a factor in the extra time being taken. |
|
Just starting to get to grips with the performance tools, I'll be heading home soon so it'll probably be tomorrow before I have anything useful from them. So far for CoreRT perf record -F 99 then perf report is showing: std::string::operator+=(char): As the most used code path (5.67%) but haven't compared with a CoreCLR run yet to see if it is different. |
|
Not sure if this helps or not but the CoreRT related sections from that code path I can see from a quick look are: 0.15% ConsoleApp1 ConsoleApp1 __GetGCStaticBase_S_P_CoreLib_System_Collections_HashHelpers |
|
This is interesting: CoreRT is allocating a bit less memory (good), but the Gen0 GCs are running more frequently (unclear whether it is good or not).
I would not expect this to show up in the profile at all. Either the symbols are wrong, or there is something very unexpected going on. Could you please try to collect with stacktraces to see where this is comming from?
The implementation of WaitHandle is quite different in CoreRT on Unix compared to CoreCLR. It maybe interesting to try to microbenchmark the exact patterns that you are exercising here. We have done microbenchmarks on the CoreRT implementation and we believe that it is good, but there can always be patterns that we have missed. The problem may not show in CPU sampling perf trace - things like context switches matter a lot for these. |
|
@jkotas, I should have realised when I posted earlier, the std:string += is due to the CoreRT code calling an unmanaged .so (via pinvoke) that is using std:string. The unmanaged .so is basically receiving updates from tcpip then notifies the .Net code via a call back which then reads the updates, again with pinvoke functions. The .Net code then puts the updates together in an collection object and passes that to a dispatcher namely - 'Thread Work item dispatcher', which dispatches the events to it's listeners. I'm not sure if the memory usage is directly related to the extra time taken in the test run but the dispatcher threads memory usage is very different in CoreRT relative to CoreCLR. CoreCLR: Thread Work item dispatcher TotalMemory: 667424 CoreRT: Thread Work item dispatcher TotalMemory: 1434040 I will carry on with getting some performance stats out of the test case, a bit pressed for time today but should be able to advance next week. What are the next steps for microbenchmarks? It does appear that our code is provoking something in the different implementation of WaitHandle in CoreRT. |
|
I've removed the use of the dispatcher threads in the test case, it's won't work in the general case but for this test case it's stable. So the above 3 dispatcher threads simply aren't created and there is no decoupling from the .so unmanaged data update thread to the end consumer events. I am still seeing a difference in time taken for the process to run: CoreCLR: Time Taken = 5084.8553 CoreRT: Time Taken = 6191.5736 So a few things to look into, I'll isolate further when I get a chance. |
|
I've tried to microbenchmark this dispatcher code using https://github.com/dotnet/BenchmarkDotNet, worked fine for CoreCLR but for CoreRT I've hit a few issues, I had to directly include the dlls from the project which was expected due to issue #2619. After that getting code generation failures: EXEC : warning : Method /home/darren/git/corert/corert/bin/Linux.x64.Release/build/Microsoft.NETCore.Native.targets(129,5): error MSB3073: The command ""/home/darren/git/corert/corert/bin/Linux.x64.Release/tools/ilc" @"obj/Release/netcoreapp2.0/native/ConsoleApp1.ilc.rsp"" exited with code 1. [/home/darren/DNAStandard/ConsoleApp1/ConsoleApp1.csproj] I'm guessing the are other tools out there that support CoreRT? |
|
Issue #2619 was fixed. The transitive close is included in the compilation if you use
This error means that there were more files missing. It should be fixed by #2619.
This means that the compiler failed. There should be "Error: " printed that describe the reason: https://github.com/dotnet/corert/blob/master/src/ILCompiler/src/Program.cs#L604 . If you can share the repro, create an issue on this please. We should look into why you do not see the Error message printed at least.
For ad-hoc micro-benchmarks, I am always using a simple for-loop and time it with StopWatch or Environment.TickCount. |
|
I was just trying a simple test from https://github.com/dotnet/BenchmarkDotNet, Using dotnet add package BenchmarkDotNet --version 0.10.10 then: using BenchmarkDotNet.Attributes; Then put [Benchmark] around a method to benchmark and in main run the benchmark: var summary = BenchmarkRunner.Run(); A bit more detail from the issue from the publish step: EXEC : error : Code generation failed [/home/darren/DNAStandard/ConsoleApp1/ConsoleApp1.csproj] I'll move onto a simple test case with a StopWatch and try to work out what is taking the extra time and I'll also try to remove various sections of code to see why the dispatching thread is taking more memory in CoreRT. |
That's a compiler bug. I'll take a look. You could work around by adding |
|
@MichalStrehovsky thanks for the information I'll give it a go. I've been looking at what provokes the dispatcher code to take more memory (and different amounts for different threads all doing nothing). Next I'll take a look at the performance difference. If you have a class with the following members declared: Then in your constructor: Then in ProcessQueue: Then add a public close method: I'm still trying to extract the parts of the code that provokes the issue but I think the above should do it, then create a few static instances: And in your main call close on them: WorkItemDispatcher.test1.Close(); It seems CoreCLR memory usage is consistent: Thread Test1 No Of Work Items Processed 0 TotalMemory: 304 CoreRT is more and varies: Thread Test1 No Of Work Items Processed 0 TotalMemory: 8280 |
CoreCLR is doing the equivalent allocations in C/C++. Seeing more managed allocations when operating with WaitHandles in CoreRT is expected, as long as it does not cause things to run slower. |
|
Ok thanks it doesn't seem related to the slow down, I'll keep investigating. |
This work has several parts that largely hook up into the existing infrastructure in the class library we built for Project N.