Skip to content
This repository was archived by the owner on Nov 13, 2026. It is now read-only.

Implement efficient/correct Comparer.get_Default and EqualityComparer.get_Default - #4935

Merged
MichalStrehovsky merged 2 commits into
dotnet:masterfrom
MichalStrehovsky:optimizeComparer
Nov 16, 2017
Merged

MichalStrehovsky merged 2 commits into
dotnet:masterfrom
MichalStrehovsky:optimizeComparer

Conversation

@MichalStrehovsky

Copy link
Copy Markdown
Member

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.

…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.
@MichalStrehovsky

Copy link
Copy Markdown
Member Author

Contributes to #763. I won't say "fixes", because there's still this thing in Array.CoreRT.cs around GetComparerForReferenceTypesOnly/StructOnlyEquals that's left.

Cc @dlewis-arcontech this might help with the perf in your benchmark.

@jkotas jkotas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

throw new NotSupportedException();
#else
// CORERT: TODO: https://github.com/dotnet/corert/issues/763
return (_default = new DefaultEqualityComparer<T>());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DefaultComparer/DefaultEqualityComparer can be deleted now (or moved under #if false if we want to keep it around for testing purposes).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes. Ifdef'd out.

TypeSystemContext context = type.Context;

if (context.IsCanonicalDefinitionType(type, CanonicalFormKind.Any) ||
(type.IsRuntimeDeterminedSubtype && !type.HasInstantiation))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this will optimize the struct X<T> : IEquatable<T> case you have been worried about properly, correct?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@dlewis-arcontech

Copy link
Copy Markdown

@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.

@MichalStrehovsky
MichalStrehovsky merged commit 39f8c07 into dotnet:master Nov 16, 2017
@MichalStrehovsky
MichalStrehovsky deleted the optimizeComparer branch November 16, 2017 10:22
@dlewis-arcontech

Copy link
Copy Markdown

Hello @MichalStrehovsky, I've rerun the tests and the commit has definitely improved the performance. Previously the results were:

Framework Run 1 (ms) Run 2 (ms) Run 3 (ms) Average (ms)
.Net Core 2.0 Ubuntu 14.04 1470 1458 1457 1462
.Net CoreRT Ubuntu 14.04 1773 1792 1779 1781

After updating the results are:

Framework Run 1 (ms) Run 2 (ms) Run 3 (ms) Average (ms)
.Net Core 2.0 Ubuntu 14.04 1473 1460 1486 1473
.Net CoreRT Ubuntu 14.04 1644 1610 1662 1639

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.

@jkotas

jkotas commented Nov 17, 2017 •

Copy link
Copy Markdown
Member

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.

ultimately would you expect the generated code on average to be more performant than the JIT code?

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.

@dlewis-arcontech

Copy link
Copy Markdown

@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.

@jkotas

jkotas commented Nov 17, 2017

Copy link
Copy Markdown
Member

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

@dlewis-arcontech

Copy link
Copy Markdown

@jkotas thanks for the information, I've added the additional code you posted above and the results are:

CoreCLR:

ServerGC: False
TotalMemory: 4075240
Gen2: 68
Gen1: 68
Gen0: 68

CoreRT:

ServerGC: False
TotalMemory: 3403872
Gen2: 68
Gen1: 68
Gen0: 93

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.

@jkotas

jkotas commented Nov 20, 2017

Copy link
Copy Markdown
Member

~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 async methods? If it is the case, #2640 is likely the reason.

A-And pushed a commit to A-And/corert that referenced this pull request Nov 20, 2017
….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.
@dlewis-arcontech

Copy link
Copy Markdown

@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?

@jkotas

jkotas commented Nov 21, 2017

Copy link
Copy Markdown
Member

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 GC.GetAllocatedBytesForCurrentThread? It will confirm or deny the theory that the more frequent GC's are caused by more allocations.

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.

MichalStrehovsky added a commit to MichalStrehovsky/corert that referenced this pull request Nov 21, 2017
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.
MichalStrehovsky added a commit to MichalStrehovsky/corert that referenced this pull request Nov 21, 2017
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.
jkotas pushed a commit that referenced this pull request Nov 21, 2017
* 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.
@dlewis-arcontech

Copy link
Copy Markdown

@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:

        Console.Write("Thread (Main Thread) ");
        Console.WriteLine($"TotalMemory: {GC.GetAllocatedBytesForCurrentThread()}");  

At the end of main it all compiles and runs fine, but for a thread if I have something like:

        this.dispatchingThread = new Thread(Process);
        this.dispatchingThread.Name = threadName;
        this.dispatchingThread.IsBackground = true;            
        this.dispatchingThread.Start();

Then at the end of process:

    private void ProcessQueue()
    { 
        ....
        Console.Write("Thread " + Thread.CurrentThread.Name + " ");
        Console.WriteLine($"TotalMemory: {GC.GetAllocatedBytesForCurrentThread()}");            
    }

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

Copy link
Copy Markdown
Member Author

GetAllocatedBytesForCurrentThread is only available in netcoreapp2.0 (i.e. it's not part of any netstandard). Is the ProcessQueue method in a different assembly that compiles against a different API set?

@dlewis-arcontech

Copy link
Copy Markdown

@MichalStrehovsky That's exactly it I'll change the project type of the assembly to .Net Core and post the results. Thanks!

@dlewis-arcontech

Copy link
Copy Markdown

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
Thread (Chain Test) TestChain1 dataset TestDataset5 TotalMemory: 13399464
Thread (Chain Test) TestChain1 dataset TestDataset3 TotalMemory: 13458920
Thread (Chain Test) TestChain1 dataset TestDataset2 TotalMemory: 13426208
Thread (Chain Test) TestChain1 dataset TestDataset1 TotalMemory: 13442272
Time Taken = 6475.7769
ServerGC: False
TotalMemory: 3901848
Gen2: 332
Gen1: 333
Gen0: 405
Thread Work item dispatcher TotalMemory: 1434040
Thread Generic events dispatcher TotalMemory: 4192
Thread Instrument Discovery dispatcher TotalMemory: 8416
Thread (Main Thread) TotalMemory: 177480

CoreCLR:

Thread (Chain Test) TestChain1 dataset TestDataset1 TotalMemory: 14095496
Thread (Chain Test) TestChain1 dataset TestDataset5 TotalMemory: 14054328
Thread (Chain Test) TestChain1 dataset TestDataset4 TotalMemory: 14094592
Thread (Chain Test) TestChain1 dataset TestDataset2 TotalMemory: 14055064
Thread (Chain Test) TestChain1 dataset TestDataset3 TotalMemory: 14094032
Time Taken = 5783.7686
ServerGC: False
TotalMemory: 7388560
Gen2: 332
Gen1: 332
Gen0: 332
Thread Work item dispatcher TotalMemory: 667424
Thread Generic events dispatcher TotalMemory: 72
Thread Instrument Discovery dispatcher TotalMemory: 72
Thread (Main Thread) TotalMemory: 193568

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.

@dlewis-arcontech

Copy link
Copy Markdown

@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.

@dlewis-arcontech

Copy link
Copy Markdown

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.

@dlewis-arcontech

Copy link
Copy Markdown

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.

@dlewis-arcontech

Copy link
Copy Markdown

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
0.15% ConsoleApp1 ConsoleApp1 __GetNonGCStaticBase_Arcontech_DotNetAPI_Arcontech_DotNetAPI_FeedApi_Feed32
0.15% ConsoleApp1 ConsoleApp1 __GetThreadStaticBase_S_P_CoreLib_System_Globalization_CultureInfo
0.15% ConsoleApp1 ConsoleApp1 __NewHelper_Arcontech_DotNetAPI_Arcontech_DotNetAPI_ChainRecord

@jkotas

jkotas commented Nov 23, 2017 •

Copy link
Copy Markdown
Member

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).

std::string::operator+=(char):

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?

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

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.

@dlewis-arcontech

dlewis-arcontech commented Nov 24, 2017 •

Copy link
Copy Markdown

@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
Thread Generic events dispatcher TotalMemory: 72 - Doing very little
Thread Instrument Discovery dispatcher TotalMemory: 72 - Doing very little

CoreRT:

Thread Work item dispatcher TotalMemory: 1434040
Thread Generic events dispatcher TotalMemory: 4192 - Doing very little
Thread Instrument Discovery dispatcher TotalMemory: 8416 - Doing very little and exactly the same as the above line which is odd why they differ

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.

@dlewis-arcontech

Copy link
Copy Markdown

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.

@dlewis-arcontech

Copy link
Copy Markdown

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 [BenchmarkDotNet.Core]BenchmarkDotNet.Portability.RuntimeInformation.GetOsVersion will always throw because: [TEMPORARY EXCEPTION MESSAGE] FileLoadErrorGeneric: Microsoft.DotNet.PlatformAbstractions [/home/darren/DNAStandard/ConsoleApp1/ConsoleApp1.csproj]

/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?

@jkotas

jkotas commented Nov 24, 2017

Copy link
Copy Markdown
Member

Issue #2619 was fixed. The transitive close is included in the compilation if you use dotnet publish -
https://github.com/dotnet/corert/blob/master/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md#using-ryujit.

FileLoadErrorGeneric: Microsoft.DotNet.PlatformAbstractions

This error means that there were more files missing. It should be fixed by #2619.

@"obj/Release/netcoreapp2.0/native/ConsoleApp1.ilc.rsp"" exited with code 1

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.

I'm guessing the are other tools out there that support CoreRT?

For ad-hoc micro-benchmarks, I am always using a simple for-loop and time it with StopWatch or Environment.TickCount.

@dlewis-arcontech

Copy link
Copy Markdown

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;
using BenchmarkDotNet.Running;

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]
ILCompiler.CodeGenerationFailedException: Code generation failed ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary2.get_Item(TKey key) at ILCompiler.ILScanResults.ScannedVTableProvider.GetSlice(TypeDesc type) in /home/darren/git/corert/corert/src/ILCompiler.Compiler/src/Compiler/ILScanner.cs:line 130 at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at ILCompiler.Compilation.HasFixedSlotVTable(TypeDesc type) in /home/darren/git/corert/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs:line 178 at Internal.JitInterface.CorInfoImpl.getCallInfo(CORINFO_RESOLVED_TOKEN& pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO& pResult) in /home/darren/git/corert/corert/src/JitInterface/src/CorInfoImpl.cs:line 3233 at Internal.JitInterface.CorInfoImpl._getCallInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN& pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO& pResult) in /home/darren/git/corert/corert/src/JitInterface/src/CorInfoBase.cs:line 2232 --- End of inner exception stack trace --- at Internal.JitInterface.CorInfoImpl.CompileMethod(IMethodCodeNode methodCodeNodeNeedingCode, MethodIL methodIL) in /home/darren/git/corert/corert/src/JitInterface/src/CorInfoImpl.cs:line 187 at ILCompiler.RyuJitCompilation.ComputeDependencyNodeDependencies(List1 obj) in /home/darren/git/corert/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilation.cs:line 72
at ILCompiler.DependencyAnalysisFramework.DependencyAnalyzer`2.ComputeMarkedNodes() in /home/darren/git/corert/corert/src/ILCompiler.DependencyAnalysisFramework/src/DependencyAnalyzer.cs:line 262
at ILCompiler.RyuJitCompilation.CompileInternal(String outputFile, ObjectDumper dumper) in /home/darren/git/corert/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilation.cs:line 39
at ILCompiler.Compilation.ILCompiler.ICompilation.Compile(String outputFile, ObjectDumper dumper) in /home/darren/git/corert/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs:line 307
at ILCompiler.Program.Run(String[] args) in /home/darren/git/corert/corert/src/ILCompiler/src/Program.cs:line 422
at ILCompiler.Program.Main(String[] args) in /home/darren/git/corert/corert/src/ILCompiler/src/Program.cs:line 576
/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/linux-x64/native/ConsoleApp1.ilc.rsp"" exited with code 1. [/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.

@MichalStrehovsky

Copy link
Copy Markdown
Member Author

ILCompiler.CodeGenerationFailedException: Code generation failed ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()

That's a compiler bug. I'll take a look. You could work around by adding <IlcArg Include="--noscan" />
to your project, but the compiler will generate less efficient code around virtual calls and generic lookups, so it's unlikely to actually help.

@dlewis-arcontech

Copy link
Copy Markdown

@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:

    private ManualResetEvent runWaitHandle = new ManualResetEvent(false);
    private ManualResetEvent exitWaitHandle = new ManualResetEvent(false);
    private WaitHandle[] waitHandles;
    private Thread dispatchingThread;

Then in your constructor:

    public WorkItemDispatcher(string threadName)
    {
            this.waitHandles = new WaitHandle[]{ runWaitHandle, exitWaitHandle };
            this.dispatchingThread = new Thread(ProcessQueue);
            this.dispatchingThread.Name = threadName; 
            this.dispatchingThread.IsBackground = true;            
            this.dispatchingThread.Start();
    }

Then in ProcessQueue:

    private void ProcessQueue()
    {      
        int noOfWorkItemsProcessed = 0;
        while (true)
        {
            if (WaitHandle.WaitAny(waitHandles) == 1)
                break;
            noOfWorkItemsProcessed++;
        }

        Console.WriteLine("Thread " + Thread.CurrentThread.Name + " No Of Work Items Processed " + noOfWorkItemsProcessed.ToString() + $" TotalMemory: {GC.GetAllocatedBytesForCurrentThread()}");  
    }

Then add a public close method:

    public void Close()
    {
            exitWaitHandle.Set();
            dispatchingThread.Join();
            runWaitHandle.Close();
            exitWaitHandle.Close();
            runWaitHandle = null;
            exitWaitHandle = null;
     }

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:

    public static readonly WorkItemDispatcher test1 = new WorkItemDispatcher("Test1");
    public static readonly WorkItemDispatcher test2 = new WorkItemDispatcher("Test2");
    public static readonly WorkItemDispatcher test3 = new WorkItemDispatcher("Test3");
    public static readonly WorkItemDispatcher test4 = new WorkItemDispatcher("Test4");
    public static readonly WorkItemDispatcher test5 = new WorkItemDispatcher("Test5");

And in your main call close on them:

WorkItemDispatcher.test1.Close();
WorkItemDispatcher.test2.Close();
WorkItemDispatcher.test3.Close();
WorkItemDispatcher.test4.Close();
WorkItemDispatcher.test5.Close();

It seems CoreCLR memory usage is consistent:

Thread Test1 No Of Work Items Processed 0 TotalMemory: 304
Thread Test2 No Of Work Items Processed 0 TotalMemory: 304
Thread Test3 No Of Work Items Processed 0 TotalMemory: 304
Thread Test4 No Of Work Items Processed 0 TotalMemory: 304
Thread Test5 No Of Work Items Processed 0 TotalMemory: 304

CoreRT is more and varies:

Thread Test1 No Of Work Items Processed 0 TotalMemory: 8280
Thread Test2 No Of Work Items Processed 0 TotalMemory: 8280
Thread Test3 No Of Work Items Processed 0 TotalMemory: 3840
Thread Test4 No Of Work Items Processed 0 TotalMemory: 8280
Thread Test5 No Of Work Items Processed 0 TotalMemory: 8280

@jkotas

jkotas commented Nov 24, 2017

Copy link
Copy Markdown
Member

It seems CoreCLR memory usage is consistent:

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.

@dlewis-arcontech

Copy link
Copy Markdown

Ok thanks it doesn't seem related to the slow down, I'll keep investigating.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants