public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)) { var options = _options.Get(context.Registration.Name); // This example will report degraded status if the application is using // more than the configured amount of memory (1gb by default). // // Additionally we include some GC info in the reported diagnostics. var allocated = GC.GetTotalMemory(forceFullCollection: false); var data = new Dictionary <string, object>() { { "Allocated", allocated }, { "AllocatedMessage", $"{allocated.GetByteCountString()} allocated is {((double)allocated / (double)options.Threshold).ToString("P0")} of the threshold of {options.Threshold.GetByteCountString()}" }, { "Gen0Collections", GC.CollectionCount(0) }, { "Gen1Collections", GC.CollectionCount(1) }, { "Gen2Collections", GC.CollectionCount(2) }, }; // Report failure if the allocated memory is >= the threshold. // // Using context.Registration.FailureStatus means that the application developer can configure // how they want failures to appear. var result = allocated >= options.Threshold ? context.Registration.FailureStatus : HealthStatus.Healthy; if (allocated >= options.Threshold) { return(Task.FromResult(HealthCheckResult.Unhealthy( description: "reports degraded status if allocated bytes >= 1gb", data: data))); } else { return(Task.FromResult(HealthCheckResult.Healthy( data: data))); } }
private void UpdateMetrics() { try { _process.Refresh(); for (var gen = 0; gen <= GC.MaxGeneration; gen++) { var collectionCount = _collectionCounts[gen]; collectionCount.Inc(GC.CollectionCount(gen) - collectionCount.Value); } _totalMemory.Set(GC.GetTotalMemory(false)); _virtualMemorySize.Set(_process.VirtualMemorySize64); _workingSet.Set(_process.WorkingSet64); _privateMemorySize.Set(_process.PrivateMemorySize64); _cpuTotal.Inc(Math.Max(0, _process.TotalProcessorTime.TotalSeconds - _cpuTotal.Value)); _openHandles.Set(_process.HandleCount); _numThreads.Set(_process.Threads.Count); } catch (Exception) { } }
public void send_err_service_thread() { JObject oKeepResponeExecute = new JObject(); try { string str = "{'hostname': '" + Environment.MachineName + "','ipaddress': '" + GetLocalIPAddress() + "','inputpath': '" + this.input.Split('\\')[this.input.Split('\\').Length - 2] + "','outputpath': '" + this.path.Split('\\')[this.path.Split('\\').Length - 2] + "','err_code': '" + this.err_code + "','email': '" + this.email + "','taxid': '" + this.taxseller + "','err_msg': '" + this.err_msg + "','actionmsg':'" + this.actionmsg + "'}"; Console.WriteLine(str + " TEST to JSON"); //string _idcomputer = this.form.label20.Text; //JObject json__idcomputer = JObject.Parse(_idcomputer); var client = new RestClient(iphost + "/api/v1/mail_err"); var request = new RestRequest(Method.POST); JObject json = JObject.Parse(str); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/json"); request.AddParameter("undefined", json.ToString(), ParameterType.RequestBody); IRestResponse response = client.Execute(request); oKeepResponeExecute = JObject.Parse(response.Content.ToString()); Console.WriteLine(oKeepResponeExecute + " ERR Service"); } catch (Exception ea) { Console.WriteLine(ea); } finally { for (int i = 0; i <= GC.MaxGeneration; i++) { int count = GC.CollectionCount(i); GC.Collect(); } GC.WaitForPendingFinalizers(); GC.SuppressFinalize(this); } }
public void StopCollectingStatistics() { if (!_isCollectingStatistics) // Already stopped { return; } _dxScene.AfterFrameRendered -= DXSceneOnAfterFrameRendered; _stopwatch.Stop(); _isCollectingStatistics = false; // Store the number of time garbage collection has occured after we started CollectingStatistics for (int i = 0; i < GC.MaxGeneration; i++) { _garbageCollectionsCount[i] = GC.CollectionCount(i) - _garbageCollectionsCount[i]; } if (_isEnabledCollectingStatistics) { DXDiagnostics.IsCollectingStatistics = false; _isEnabledCollectingStatistics = false; } }
static void Concurrency() { Console.WriteLine("Concurrency och minneshantering. (2ggr)"); Console.ReadKey(); for (int y = 0; y < 2; y++) { int remaining = 20_000_000; var mres = new ManualResetEventSlim(); WaitCallback wc = null; wc = delegate { if (Interlocked.Decrement(ref remaining) <= 0) { mres.Set(); } else { ThreadPool.QueueUserWorkItem(wc); } }; var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); sw.Start(); for (int i = 0; i < Environment.ProcessorCount; i++) { ThreadPool.QueueUserWorkItem(wc); } mres.Wait(); Console.WriteLine($"Elapsed={sw.Elapsed} Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}"); } Console.ReadKey(); Console.WriteLine(); }
private static void _pruneCachedTraceSources() { lock (s_tracesources) { if (s_LastCollectionCount != GC.CollectionCount(2)) { List <WeakReference <TraceSource> > buffer = new List <WeakReference <TraceSource> >(s_tracesources.Count); for (int i = 0; i < s_tracesources.Count; i++) { if (s_tracesources[i].TryGetTarget(out _)) { buffer.Add(s_tracesources[i]); } } if (buffer.Count < s_tracesources.Count) { s_tracesources.Clear(); s_tracesources.AddRange(buffer); s_tracesources.TrimExcess(); } s_LastCollectionCount = GC.CollectionCount(2); } } }
public IEnumerator OnUpdate() { while (!m_stop) { int collCount = GC.CollectionCount(0); if (Math.Abs(m_lastCollectNum - collCount) > Mathf.Epsilon) { m_lastCollectNum = collCount; m_delta = Time.realtimeSinceStartup - m_lastCollect; m_lastCollect = Time.realtimeSinceStartup; m_lastDeltaTime = Time.deltaTime; m_collectAlloc = m_allocMem; } m_allocMem = GC.GetTotalMemory(false); m_peakAlloc = m_allocMem > m_peakAlloc ? m_allocMem : m_peakAlloc; if (!(Time.realtimeSinceStartup - m_lastAllocSet > 0.3f)) { yield return(new WaitForSeconds(1.0f)); } long diff = m_allocMem - m_lastAllocMemory; m_lastAllocMemory = m_allocMem; m_lastAllocSet = Time.realtimeSinceStartup; if (diff >= 0) { m_allocRate = diff; } yield return(new WaitForSeconds(1.0f)); } }
private static void Logout(Session session) { Console.WriteLine("Logged out"); Thread.EndThreadAffinity(); GC0 = GC.CollectionCount(0) - GC0; GC1 = GC.CollectionCount(1) - GC1; GC2 = GC.CollectionCount(2) - GC2; Console.WriteLine(); Console.WriteLine("Orders: " + Orders); Console.WriteLine("Filled: " + Executions); Console.WriteLine(); Console.WriteLine($"GC 0: {GC0}"); Console.WriteLine($"GC 1: {GC1}"); Console.WriteLine($"GC 2: {GC2}"); Console.WriteLine(); Console.WriteLine("---------------------"); Console.WriteLine(); Console.WriteLine("Waiting for client..."); Console.WriteLine(); }
private void _setLabelText() { sb.Clear(); if (showFrameInfo) { sb.Append($"{fpsPerf.GetHistoryString(this.labelUpdateFrequency)}"); sb.Append($"\n{totalFramePerf.GetHistoryString(this.labelUpdateFrequency) }"); sb.Append($"\n{treeEndHelper.insideTreePerf.GetHistoryString(this.labelUpdateFrequency)}"); sb.Append($"\n{treeEndHelper.outsideTreePerf.GetHistoryString(this.labelUpdateFrequency)}"); sb.Append($"\n"); } if (showPhysicInfo) { var phyInterpFrac = Engine.GetPhysicsInterpolationFraction(); var phyInFrame = Engine.IsInPhysicsFrame(); var phyItterPerSec = Engine.IterationsPerSecond; var activeObjects = PhysicsServer.GetProcessInfo(PhysicsServer.ProcessInfo.ActiveObjects); var collisionPairs = PhysicsServer.GetProcessInfo(PhysicsServer.ProcessInfo.CollisionPairs); var islandCount = PhysicsServer.GetProcessInfo(PhysicsServer.ProcessInfo.IslandCount); sb.Append($"\nPhysics: Itter/sec={phyItterPerSec} inPhyFrame={phyInFrame} interpFrac={phyInterpFrac.ToString("F2")} activeObj={activeObjects} colPairs={collisionPairs} islands={islandCount}"); } if (showGcInfo) { var totMem = GC.GetTotalMemory(false) / 1024; var gcCount = new int[] { GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2) }; sb.Append($"\nGC: Collects/Gen={string.Join(",", gcCount)} ({totMem}K Total Alloc)"); } label.Text = sb.ToString(); }
public void Dispose() { Console.WriteLine("{0} (GCs={1,3}) {2}", (m_stopwatch.Elapsed), GC.CollectionCount(0) - m_collectionCount, m_text); }
public static void Calibrate() { OffsetGen0 = GC.CollectionCount(0); OffsetGen1 = GC.CollectionCount(1); OffsetGen2 = GC.CollectionCount(2); }
protected override void OnEventCommand(EventCommandEventArgs command) { if (command.Command == EventCommand.Enable) { // NOTE: These counters will NOT be disposed on disable command because we may be introducing // a race condition by doing that. We still want to create these lazily so that we aren't adding // overhead by at all times even when counters aren't enabled. // On disable, PollingCounters will stop polling for values so it should be fine to leave them around. _cpuTimeCounter ??= new PollingCounter("cpu-usage", this, () => RuntimeEventSourceHelper.GetCpuUsage()) { DisplayName = "CPU Usage", DisplayUnits = "%" }; _workingSetCounter ??= new PollingCounter("working-set", this, () => (double)(Environment.WorkingSet / 1_000_000)) { DisplayName = "Working Set", DisplayUnits = "MB" }; _gcHeapSizeCounter ??= new PollingCounter("gc-heap-size", this, () => (double)(GC.GetTotalMemory(false) / 1_000_000)) { DisplayName = "GC Heap Size", DisplayUnits = "MB" }; _gen0GCCounter ??= new IncrementingPollingCounter("gen-0-gc-count", this, () => GC.CollectionCount(0)) { DisplayName = "Gen 0 GC Count", DisplayRateTimeScale = new TimeSpan(0, 1, 0) }; _gen1GCCounter ??= new IncrementingPollingCounter("gen-1-gc-count", this, () => GC.CollectionCount(1)) { DisplayName = "Gen 1 GC Count", DisplayRateTimeScale = new TimeSpan(0, 1, 0) }; _gen2GCCounter ??= new IncrementingPollingCounter("gen-2-gc-count", this, () => GC.CollectionCount(2)) { DisplayName = "Gen 2 GC Count", DisplayRateTimeScale = new TimeSpan(0, 1, 0) }; _threadPoolThreadCounter ??= new PollingCounter("threadpool-thread-count", this, () => ThreadPool.ThreadCount) { DisplayName = "ThreadPool Thread Count" }; _monitorContentionCounter ??= new IncrementingPollingCounter("monitor-lock-contention-count", this, () => Monitor.LockContentionCount) { DisplayName = "Monitor Lock Contention Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) }; _threadPoolQueueCounter ??= new PollingCounter("threadpool-queue-length", this, () => ThreadPool.PendingWorkItemCount) { DisplayName = "ThreadPool Queue Length" }; _completedItemsCounter ??= new IncrementingPollingCounter("threadpool-completed-items-count", this, () => ThreadPool.CompletedWorkItemCount) { DisplayName = "ThreadPool Completed Work Item Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) }; _allocRateCounter ??= new IncrementingPollingCounter("alloc-rate", this, () => GC.GetTotalAllocatedBytes()) { DisplayName = "Allocation Rate", DisplayUnits = "B", DisplayRateTimeScale = new TimeSpan(0, 0, 1) }; _timerCounter ??= new PollingCounter("active-timer-count", this, () => Timer.ActiveCount) { DisplayName = "Number of Active Timers" }; _fragmentationCounter ??= new PollingCounter("gc-fragmentation", this, () => { var gcInfo = GC.GetGCMemoryInfo(); return(gcInfo.HeapSizeBytes != 0 ? gcInfo.FragmentedBytes * 100d / gcInfo.HeapSizeBytes : 0); }) { DisplayName = "GC Fragmentation", DisplayUnits = "%" }; _committedCounter ??= new PollingCounter("gc-committed", this, () => (double)(GC.GetGCMemoryInfo().TotalCommittedBytes / 1_000_000)) { DisplayName = "GC Committed Bytes", DisplayUnits = "MB" }; _exceptionCounter ??= new IncrementingPollingCounter("exception-count", this, () => Exception.GetExceptionCount()) { DisplayName = "Exception Count", DisplayRateTimeScale = new TimeSpan(0, 0, 1) }; _gcTimeCounter ??= new PollingCounter("time-in-gc", this, () => GC.GetLastGCPercentTimeInGC()) { DisplayName = "% Time in GC since last GC", DisplayUnits = "%" }; _gen0SizeCounter ??= new PollingCounter("gen-0-size", this, () => GC.GetGenerationSize(0)) { DisplayName = "Gen 0 Size", DisplayUnits = "B" }; _gen1SizeCounter ??= new PollingCounter("gen-1-size", this, () => GC.GetGenerationSize(1)) { DisplayName = "Gen 1 Size", DisplayUnits = "B" }; _gen2SizeCounter ??= new PollingCounter("gen-2-size", this, () => GC.GetGenerationSize(2)) { DisplayName = "Gen 2 Size", DisplayUnits = "B" }; _lohSizeCounter ??= new PollingCounter("loh-size", this, () => GC.GetGenerationSize(3)) { DisplayName = "LOH Size", DisplayUnits = "B" }; _pohSizeCounter ??= new PollingCounter("poh-size", this, () => GC.GetGenerationSize(4)) { DisplayName = "POH (Pinned Object Heap) Size", DisplayUnits = "B" }; _assemblyCounter ??= new PollingCounter("assembly-count", this, () => System.Reflection.Assembly.GetAssemblyCount()) { DisplayName = "Number of Assemblies Loaded" }; _ilBytesJittedCounter ??= new PollingCounter("il-bytes-jitted", this, () => System.Runtime.JitInfo.GetCompiledILBytes()) { DisplayName = "IL Bytes Jitted", DisplayUnits = "B" }; _methodsJittedCounter ??= new PollingCounter("methods-jitted-count", this, () => System.Runtime.JitInfo.GetCompiledMethodCount()) { DisplayName = "Number of Methods Jitted" }; _jitTimeCounter ??= new IncrementingPollingCounter("time-in-jit", this, () => System.Runtime.JitInfo.GetCompilationTime().TotalMilliseconds) { DisplayName = "Time spent in JIT", DisplayUnits = "ms", DisplayRateTimeScale = new TimeSpan(0, 0, 1) }; AppContext.LogSwitchValues(this); } } } }
public void ExecuteTest(string testName, int threadCount, int messageCount, Action <string, object[]> logMethod, Action flushMethod) { var currentProcess = Process.GetCurrentProcess(); if (Environment.ProcessorCount > 1) { if (threadCount <= 1) { currentProcess.PriorityClass = ProcessPriorityClass.High; } else { currentProcess.PriorityClass = ProcessPriorityClass.AboveNormal; } } #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 long threadAllocationTotal = 0; #endif Action <object> threadAction = (state) => { int threadMessageCount = (int)state; #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 long allocatedBytesForCurrentThread = GC.GetAllocatedBytesForCurrentThread(); #endif for (int i = 0; i < threadMessageCount; i += _messageTemplates.Count) { for (int j = 0; j < _messageTemplates.Count; ++j) { logMethod(_messageTemplates[j], _messageArgs); } } #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 System.Threading.Interlocked.Add(ref threadAllocationTotal, GC.GetAllocatedBytesForCurrentThread() - allocatedBytesForCurrentThread); #endif }; int warmUpCount = messageCount > 100000 * 2 ? 100000 : messageCount / 10; Console.WriteLine(string.Format("Executing warmup run... (.NET={0}, Platform={1}bit)", FileVersionInfo.GetVersionInfo(typeof(int).Assembly.Location).ProductVersion, IntPtr.Size * 8)); RunTest(threadAction, 1, warmUpCount / _messageTemplates.Count); // Warmup run GC.Collect(2, GCCollectionMode.Forced, true); #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 #else AppDomain.MonitoringIsEnabled = true; #endif System.Threading.Thread.Sleep(2000); // Allow .NET runtime to do its background thing, before we start Console.WriteLine("Executing performance test..."); Console.WriteLine(""); Console.WriteLine("| Test Name | Messages | Size | Args | Threads |"); Console.WriteLine("|------------------|------------|------|------|---------|"); Console.WriteLine("| {0,-16} | {1,10:N0} | {2,4} | {3,4} | {4,7} |", testName, messageCount, _messageTemplates[0].Length, _messageArgs.Length, threadCount); Console.WriteLine(""); Stopwatch stopWatch = new Stopwatch(); int gc2count = GC.CollectionCount(2); int gc1count = GC.CollectionCount(1); int gc0count = GC.CollectionCount(0); #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 threadAllocationTotal = 0; #else long allocatedBytes = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize; #endif TimeSpan cpuTimeBefore = currentProcess.TotalProcessorTime; int countPerThread = (int)((messageCount - 1) / (double)threadCount); int actualMessageCount = countPerThread * threadCount; stopWatch.Start(); RunTest(threadAction, threadCount, countPerThread); // Real performance run flushMethod(); stopWatch.Stop(); TimeSpan cpuTimeAfter = currentProcess.TotalProcessorTime; #if NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 long deltaAllocatedBytes = threadAllocationTotal; #else long deltaAllocatedBytes = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize - allocatedBytes; #endif // Show report message. var throughput = actualMessageCount / ((double)stopWatch.ElapsedTicks / Stopwatch.Frequency); Console.WriteLine(""); Console.WriteLine("| Test Name | Time (ms) | Msgs/sec | GC2 | GC1 | GC0 | CPU (ms) | Alloc (MB) |"); Console.WriteLine("|------------------|-----------|-----------|-----|-----|-----|----------|------------|"); Console.WriteLine( string.Format("| {0,-16} | {1,9:N0} | {2,9:N0} | {3,3} | {4,3} | {5,3} | {6,8:N0} | {7,10:N1} |", testName, stopWatch.ElapsedMilliseconds, (long)throughput, GC.CollectionCount(2) - gc2count, GC.CollectionCount(1) - gc1count, GC.CollectionCount(0) - gc0count, (int)(cpuTimeAfter - cpuTimeBefore).TotalMilliseconds, deltaAllocatedBytes / 1024.0 / 1024.0)); if (stopWatch.ElapsedMilliseconds < 5000) { Console.WriteLine("!!! Test completed too quickly, to give useful numbers !!!"); } if (!Stopwatch.IsHighResolution) { Console.WriteLine("!!! Stopwatch.IsHighResolution = False !!!"); } #if DEBUG Console.WriteLine("!!! Using DEBUG build !!!"); #endif }
public void SteadyState() { Console.WriteLine(_index + ": replacing old every " + _old_time + "; med every " + _med_time + ";creating young " + _young_time + "times (" + "(size " + _mean_young_alloc_size + ")"); Console.WriteLine("iterating {0} times", _iter_count); int iter_interval = _iter_count / 10; Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); //int lastGen2Count = 0; int lastGen1Count = 0; int checkInterval = _old.Length / 10; int lastChecked = 0; int iCheckedEnd = 0; int timeoutInterval = 5; double pinRatio = 0.1; bool fIsPinned = false; int iPinInterval = (int)((double)1 / pinRatio); Console.WriteLine("Pinning every {0} object", iPinInterval); int iNextPin = _rand.getRand(iPinInterval * 4) + 1; int iPinnedObject = 0; int iPinnedMidSize = _mean_old_alloc_size * 2; int countObjects = 0; int countObjectsGen1 = 0; int[] countWithGen = new int[3]; MiddlePin[] steadyPinningArray = new MiddlePin[100]; GCHandle[] steadyPinningHandles = new GCHandle[100]; int steadyPinningIndex = 0; for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++) { steadyPinningArray[steadyPinningIndex] = new MiddlePin(); steadyPinningHandles[steadyPinningIndex] = new GCHandle(); } for (int j = 0; j < _iter_count; j++) { if (steadyPinningIndex >= steadyPinningArray.Length) { steadyPinningIndex = 0; // Console.WriteLine("steady array wrapped, press enter to continue"); // Console.ReadLine(); } byte[] tempObj = new byte[1]; steadyPinningArray[steadyPinningIndex].smallNonePinned = new byte[8]; steadyPinningArray[steadyPinningIndex].pinnedObj = new byte[8]; steadyPinningArray[steadyPinningIndex].nonePinned = new byte[24]; steadyPinningHandles[steadyPinningIndex] = GCHandle.Alloc(steadyPinningArray[steadyPinningIndex].pinnedObj, GCHandleType.Pinned); steadyPinningArray[steadyPinningIndex].smallNonePinned[3] = 0x31; steadyPinningArray[steadyPinningIndex].smallNonePinned[5] = 0x51; steadyPinningArray[steadyPinningIndex].smallNonePinned[7] = 0x71; steadyPinningArray[steadyPinningIndex].pinnedObj[3] = 0x21; steadyPinningArray[steadyPinningIndex].pinnedObj[5] = 0x41; steadyPinningArray[steadyPinningIndex].pinnedObj[7] = 0x61; tempObj = new byte[256]; steadyPinningIndex++; countObjects = 0; countObjectsGen1 = 0; iCheckedEnd = lastChecked + checkInterval; if (iCheckedEnd > _old.Length) { iCheckedEnd = _old.Length; } //Console.WriteLine("timing out item {0} to {1}", lastChecked, iCheckedEnd); // time out requests in this range. // for the range we are looking at time out requests (ie, end them and replace them with new ones). // we go from the beginning of the range to the end, time out every Nth one; then time out everyone // after that, and so on. for (int iIter = 0; iIter < timeoutInterval; iIter++) { for (int iCheckIndex = 0; iCheckIndex < ((iCheckedEnd - lastChecked) / timeoutInterval); iCheckIndex++) { int iItemIndex = (lastChecked + iCheckIndex * timeoutInterval + iIter) % _old.Length; // Console.WriteLine("replacing item {0}", iItemIndex); _old[iItemIndex].Free(); countObjects++; if ((countObjects % 10) == 0) { byte[] temp = new byte[_mean_med_alloc_size * 3]; temp[0] = (byte)27; // 0x1b } else if ((countObjects % 4) == 0) { byte[] temp = new byte[1]; temp[0] = (byte)27; // 0x1b } if (countObjects == iNextPin) { fIsPinned = true; iNextPin += _rand.getRand(iPinInterval * 4) + 1; } else { fIsPinned = false; } iPinnedMidSize = _mean_old_alloc_size * 2; if (fIsPinned) { iPinnedObject++; if ((iPinnedObject % 10) == 0) { iPinnedMidSize = _mean_old_alloc_size * 10; } } //Console.WriteLine("perm {0}, mid {1}, {2}", mean_old_alloc_size, iPinnedMidSize, (fIsPinned ? "pinned" : "not pinned")); _old[iItemIndex] = new MyRequest(_mean_old_alloc_size, iPinnedMidSize, fIsPinned); } } for (int i = 0; i < 3; i++) { countWithGen[i] = 0; } // Console.WriteLine("Checking {0} to {1}", lastChecked, iCheckedEnd); for (int iItemIndex = lastChecked; iItemIndex < iCheckedEnd; iItemIndex++) { //int iGen = GC.GetGeneration(old[iItemIndex].mObj); int iGen = _rand.getRand(3); countWithGen[iGen]++; if (iGen == 1) { //Console.WriteLine("item {0} is in gen1, getting rid of it", iItemIndex); if ((countObjectsGen1 % 5) == 0) { _old[iItemIndex].mObj = null; } countObjectsGen1++; } } // Console.WriteLine("{0} in gen0, {1} in gen1, {2} in gen2", // countWithGen[0], // countWithGen[1], // countWithGen[2]); // // Console.WriteLine("{0} objects out of {1} are in gen1", countObjectsGen1, (iCheckedEnd - lastChecked)); if (iCheckedEnd == _old.Length) { lastChecked = 0; } else { lastChecked += checkInterval; } int currentGen1Count = GC.CollectionCount(1); if ((currentGen1Count - lastGen1Count) > 30) { GC.Collect(2, GCCollectionMode.Forced, false); Console.WriteLine("{0}: iter {1}, heap size: {2}", _index, j, GC.GetTotalMemory(false)); lastGen1Count = currentGen1Count; } } for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++) { if (steadyPinningHandles[steadyPinningIndex].IsAllocated) { steadyPinningHandles[steadyPinningIndex].Free(); } } stopwatch.Stop(); Console.WriteLine("{0}: steady: {1:d} seconds({2:d} ms. Heap size {3})", _index, (int)stopwatch.Elapsed.TotalSeconds, (int)stopwatch.Elapsed.TotalMilliseconds, GC.GetTotalMemory(false)); }
/// <summary>真正的计时</summary> protected virtual void TimeTrue() { if (Times <= 0) { throw new Exception("非法迭代次数!"); } // 统计GC代数 GC.Collect(GC.MaxGeneration); gen = new Int32[GC.MaxGeneration + 1]; for (Int32 i = 0; i <= GC.MaxGeneration; i++) { gen[i] = GC.CollectionCount(i); } Stopwatch watch = new Stopwatch(); watch.Start(); cpuCycles = GetCycleCount(); threadTime = GetCurrentThreadTimes(); // 如果未指定迭代方法,则使用内部的Time Action <Int32> action = Action; if (action == null) { action = Time; // 初始化 Init(); } for (Int32 i = 0; i < Times; i++) { Index = i; action(i); } if (Action == null) { // 结束 Finish(); } CpuCycles = (long)(GetCycleCount() - cpuCycles); ThreadTime = GetCurrentThreadTimes() - threadTime; watch.Stop(); Elapsed = watch.Elapsed; // 统计GC代数 List <Int32> list = new List <Int32>(); for (Int32 i = 0; i <= GC.MaxGeneration; i++) { int count = GC.CollectionCount(i) - gen[i]; list.Add(count); } Gen = list.ToArray(); }
public void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime) { FrameNumber++; if (Viewer.RealTime - LastUpdateRealTime >= 0.25) { double elapsedRealSeconds = Viewer.RealTime - LastUpdateRealTime; LastUpdateRealTime = Viewer.RealTime; Profile(elapsedRealSeconds); } #if DEBUG_DUMP_STEAM_POWER_CURVE if (IsRecordingSteamPowerCurve) { RecordSteamPowerCurve(); } else { #endif if (IsRecordingSteamPerformance) { RecordSteamPerformance(); } else //Here's where the logger stores the data from each frame if (Viewer.Settings.DataLogger) { Logger.Separator = (DataLogger.Separators)Enum.Parse(typeof(DataLogger.Separators), Viewer.Settings.DataLoggerSeparator); if (Viewer.Settings.DataLogPerformance) { Logger.Data(VersionInfo.Version); Logger.Data(FrameNumber.ToString("F0")); Logger.Data(GetWorkingSetSize().ToString("F0")); Logger.Data(GC.GetTotalMemory(false).ToString("F0")); Logger.Data(GC.CollectionCount(0).ToString("F0")); Logger.Data(GC.CollectionCount(1).ToString("F0")); Logger.Data(GC.CollectionCount(2).ToString("F0")); Logger.Data(ProcessorCount.ToString("F0")); Logger.Data(Viewer.RenderProcess.FrameRate.Value.ToString("F0")); Logger.Data(Viewer.RenderProcess.FrameTime.Value.ToString("F6")); Logger.Data(Viewer.RenderProcess.ShadowPrimitivePerFrame.Sum().ToString("F0")); Logger.Data(Viewer.RenderProcess.PrimitivePerFrame.Sum().ToString("F0")); Logger.Data(Viewer.RenderProcess.Profiler.Wall.Value.ToString("F0")); Logger.Data(Viewer.UpdaterProcess.Profiler.Wall.Value.ToString("F0")); Logger.Data(Viewer.LoaderProcess.Profiler.Wall.Value.ToString("F0")); Logger.Data(Viewer.SoundProcess.Profiler.Wall.Value.ToString("F0")); } if (Viewer.Settings.DataLogPhysics) { Logger.Data(FormatStrings.FormatPreciseTime(Viewer.Simulator.ClockTime)); Logger.Data(Viewer.PlayerLocomotive.Direction.ToString()); Logger.Data(Viewer.PlayerTrain.MUReverserPercent.ToString("F0")); Logger.Data(Viewer.PlayerLocomotive.ThrottlePercent.ToString("F0")); Logger.Data(Viewer.PlayerLocomotive.MotiveForceN.ToString("F0")); Logger.Data(Viewer.PlayerLocomotive.BrakeForceN.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).LocomotiveAxle.AxleForceN.ToString("F2")); Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).LocomotiveAxle.SlipSpeedPercent.ToString("F1")); switch (Viewer.Settings.DataLogSpeedUnits) { case "route": Logger.Data(FormatStrings.FormatSpeed(Viewer.PlayerLocomotive.SpeedMpS, Viewer.MilepostUnitsMetric)); break; case "mps": Logger.Data(Viewer.PlayerLocomotive.SpeedMpS.ToString("F1")); break; case "mph": Logger.Data(MpS.FromMpS(Viewer.PlayerLocomotive.SpeedMpS, false).ToString("F1")); break; case "kmph": Logger.Data(MpS.FromMpS(Viewer.PlayerLocomotive.SpeedMpS, true).ToString("F1")); break; default: Logger.Data(FormatStrings.FormatSpeed(Viewer.PlayerLocomotive.SpeedMpS, Viewer.MilepostUnitsMetric)); break; } Logger.Data((Viewer.PlayerLocomotive.DistanceM.ToString("F0"))); Logger.Data((Viewer.PlayerLocomotive.GravityForceN.ToString("F0"))); if ((Viewer.PlayerLocomotive as MSTSLocomotive).TrainBrakeController != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).TrainBrakeController.CurrentValue.ToString("F2")); } else { Logger.Data("null"); } if ((Viewer.PlayerLocomotive as MSTSLocomotive).EngineBrakeController != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).EngineBrakeController.CurrentValue.ToString("F2")); } else { Logger.Data("null"); } Logger.Data(Viewer.PlayerLocomotive.BrakeSystem.GetCylPressurePSI().ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).MainResPressurePSI.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSLocomotive).CompressorIsOn.ToString()); #if GEARBOX_DEBUG_LOG if (Viewer.PlayerLocomotive.GetType() == typeof(MSTSDieselLocomotive)) { Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].RealRPM.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].DemandedRPM.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].LoadPercent.ToString("F0")); if ((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines.HasGearBox) { Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].GearBox.CurrentGearIndex.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].GearBox.NextGearIndex.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselEngines[0].GearBox.ClutchPercent.ToString()); } else { Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); } Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselFlowLps.ToString("F2")); Logger.Data((Viewer.PlayerLocomotive as MSTSDieselLocomotive).DieselLevelL.ToString("F0")); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); } if (Viewer.PlayerLocomotive.GetType() == typeof(MSTSElectricLocomotive)) { Logger.Data((Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs[1].CommandUp.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs[2].CommandUp.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs.List.Count > 2 ? (Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs[3].CommandUp.ToString() : null); Logger.Data((Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs.List.Count > 3 ? (Viewer.PlayerLocomotive as MSTSElectricLocomotive).Pantographs[4].CommandUp.ToString() : null); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); Logger.Data("null"); } if (Viewer.PlayerLocomotive.GetType() == typeof(MSTSSteamLocomotive)) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).BlowerSteamUsageLBpS.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).BoilerPressurePSI.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).CylinderCocksAreOpen.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).CylinderCompoundOn.ToString()); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).EvaporationLBpS.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).FireMassKG.ToString("F0")); Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).CylinderSteamUsageLBpS.ToString("F0")); if ((Viewer.PlayerLocomotive as MSTSSteamLocomotive).BlowerController != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).BlowerController.CurrentValue.ToString("F0")); } else { Logger.Data("null"); } if ((Viewer.PlayerLocomotive as MSTSSteamLocomotive).DamperController != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).DamperController.CurrentValue.ToString("F0")); } else { Logger.Data("null"); } if ((Viewer.PlayerLocomotive as MSTSSteamLocomotive).FiringRateController != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).FiringRateController.CurrentValue.ToString("F0")); } else { Logger.Data("null"); } if ((Viewer.PlayerLocomotive as MSTSSteamLocomotive).Injector1Controller != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).Injector1Controller.CurrentValue.ToString("F0")); } else { Logger.Data("null"); } if ((Viewer.PlayerLocomotive as MSTSSteamLocomotive).Injector2Controller != null) { Logger.Data((Viewer.PlayerLocomotive as MSTSSteamLocomotive).Injector2Controller.CurrentValue.ToString("F0")); } else { Logger.Data("null"); } } #endif } Logger.End(); #if DEBUG_DUMP_STEAM_POWER_CURVE } #endif } }
public string GetGCCount(ParseState state) { state.msg($"Gc0:{GC.CollectionCount(0)} GC1:{GC.CollectionCount(1)} GC2:{GC.CollectionCount(2)}"); state.msg($"{GC.GetTotalMemory(false)}"); return(success); }
public static void ParallelTime ( string name , int iterations , Action actionOnce , int maxDegreeOfParallelism //= 1 , MultiPerformanceCountersTypeFlags enablePerformanceCounters //= false , string performanceCountersCategoryName , string performanceCountersCategoryInstanceName ) { // 1. ConsoleColor currentForeColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(name); // 2. GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); int[] gcCounts = new int[GC.MaxGeneration + 1]; for (int i = 0; i <= GC.MaxGeneration; i++) { gcCounts[i] = GC.CollectionCount(i); } IntPtr threadID = GetCurrentThreadId(); Stopwatch watch = Stopwatch.StartNew(); ulong cycleCount = GetCurrentThreadCycleCount(); #if NET45 //#endif Parallel.For ( 0 , iterations , new ParallelOptions() { MaxDegreeOfParallelism = maxDegreeOfParallelism //, TaskScheduler = null } , (x) => { EasyPerformanceCountersHelper <SessionsPerformanceCountersContainer> .CountPerformance ( enablePerformanceCounters , performanceCountersCategoryName , performanceCountersCategoryInstanceName , null , actionOnce , null , null , null ); } ); //#if NET45 #endif ulong cpuCycles = GetCurrentThreadCycleCount() - cycleCount; watch.Stop(); //watch = null; // 4. Console.ForegroundColor = currentForeColor; Console.WriteLine ( "{0}Time Elapsed:{0}{1}ms" , "\t" , watch.ElapsedMilliseconds.ToString("N0") ); Console.WriteLine ( "{0}CPU Cycles:{0}{1}" , "\t" , cpuCycles.ToString("N0") ); // 5. for (int i = 0; i <= GC.MaxGeneration; i++) { int count = GC.CollectionCount(i) - gcCounts[i]; Console.WriteLine ( "{0}Gen{1}:{0}{0}{2}" , "\t" , i , count ); } Console.WriteLine(); }
public async Task BenchWithConstraints(int cx) { var collects = Enumerable.Range(0, 3).Select(i => GC.CollectionCount(i)).ToArray(); long nb = 0; store = await StoreBuilder.New().CreateAsync(); schema = await store.Schemas.New <TestDomainDefinition>().CreateAsync(); var domain = await store.DomainModels .New() .UsingIdGenerator(services => new Hyperstore.Modeling.Domain.LongIdGenerator()) .CreateAsync("Test"); var sw = new Stopwatch(); var mx = 10000; Console.WriteLine("Benchmark manipulating {0} elements...", mx); // Adding 100 constraints on each element var nbc = 100; if (cx % 2 == 1) { Console.WriteLine("Adding 100 implicit constraints on each element."); for (int i = 0; i < nbc; i++) { schema.Definition.XExtendsBaseClass.AddImplicitConstraint(self => System.Threading.Interlocked.Increment(ref nb) > 0, "OK").Register(); } } Console.WriteLine("Running..."); sw.Start(); AddElement(domain, mx); Console.WriteLine("Added in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); UpdateElement(mx); Console.WriteLine("Updated in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); ReadElement(mx); Console.WriteLine("Read in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); RemoveElement(mx); Console.WriteLine("Removed in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); sw.Stop(); Console.WriteLine("Expected {0} Value {1}", mx * nbc * 2, nb); domain = null; store.Dispose(); ids.Clear(); for (int i = 0; i < 3; i++) { Console.WriteLine("GC collection {0} : {1}", i, GC.CollectionCount(i) - collects[i]); } //Console.WriteLine(); GC.Collect(); GC.WaitForPendingFinalizers(); //Assert.AreEqual(mx * nbc * 2, nb); // Nbre de fois la contrainte est appelée (sur le add et le update) //Assert.IsTrue(sw.ElapsedMilliseconds < 3000, String.Format("ElapsedTime = {0}", sw.ElapsedMilliseconds)); }
// This value can be computed separately and hard-coded into the application. // The method is included to illustrate the technique. private static int EstimateMemoryUsageInMB() { int memUsageInMB = 0; long memBefore = GC.GetTotalMemory(true); int numGen0Collections = GC.CollectionCount(0); // Execute a test version of the method to estimate memory requirements. // This test method only exists to determine the memory requirements. ThreadMethod(); // Includes garbage generated by the worker function. long memAfter = GC.GetTotalMemory(false); // If a garbage collection occurs during the measuring, you might need a greater memory requirement. Console.WriteLine("Did a GC occur while measuring? {0}", numGen0Collections == GC.CollectionCount(0)); // Set the field used as the parameter for the MemoryFailPoint constructor. long memUsage = (memAfter - memBefore); if (memUsage < 0) { Console.WriteLine("GC's occurred while measuring memory usage. Try measuring again."); memUsage = 1 << 20; } // Round up to the nearest MB. memUsageInMB = (int)(1 + (memUsage >> 20)); Console.WriteLine("Memory usage estimate: {0} bytes, rounded to {1} MB", memUsage, memUsageInMB); return(memUsageInMB); }
public static int Main(string[] args) { if (GCSettings.IsServerGC == true) { Console.WriteLine("we are using server GC"); } int iter_num = 500000; if (args.Length >= 1) { iter_num = int.Parse(args[0]); Console.WriteLine("iterating {0} times", iter_num); } // For now just do everything on the main thread. //int threadCount = 8; // int threadCount = 1; // if (args.Length >= 2) // { // threadCount = int.Parse(args[1]); // Console.WriteLine ("creating {0} threads", threadCount); // } long tStart, tEnd; tStart = Environment.TickCount; // MyThread t; // ThreadStart ts; // Thread[] threads = new Thread[threadCount]; // // for (int i = 0; i < threadCount; i++) // { // t = new MyThread(i, iter_num, old, med); // ts = new ThreadStart(t.TimeTest); // threads[i] = new Thread( ts ); // threads[i].Start(); // } // // for (int i = 0; i < threadCount; i++) // { // threads[i].Join(); // } // Console.WriteLine("start with {0} gen1 GCs", s_iLastGen1Count); s_iLastGen0Count = GC.CollectionCount(0); s_iLastGen1Count = GC.CollectionCount(1); for (int iter = 0; iter < 1; iter++) { MemoryAlloc[] maArr = new MemoryAlloc[16]; Rand rand = new Rand(); for (int i = 0; i < maArr.Length; i++) { maArr[i] = new MemoryAlloc(rand.getRand(500), rand, i); maArr[i].AllocTest(); //Console.WriteLine("{0} allocated", i); InducedGen2(); for (int iAllocated = 0; iAllocated < i; iAllocated++) { //Console.WriteLine("creating fragmentation in obj {0}", iAllocated); maArr[iAllocated].CreateFragmentation(); InducedGen2(); } } for (int i = 0; i < maArr.Length; i++) { InducedGen2(); Console.WriteLine("steady state for " + i); maArr[i].SteadyState(); Console.WriteLine("DONE: steady state for " + i); } } tEnd = Environment.TickCount; Console.WriteLine("Test completed; " + (tEnd - tStart) + "ms"); // Console.WriteLine("Press any key to exit."); // Console.ReadLine(); return(100); }
public OperationTimer(string txt) { m_collectionCount = GC.CollectionCount(0); }
private GcNotification(Func <object, bool> callback, object state) { _callback = callback; _state = state; _initialCollectionCount = GC.CollectionCount(2); }
private static void ConcurrentQueueBench(Action <string> log, int concurrency) { log($"{nameof(ConcurrentQueueBench)} starting with {concurrency} threads..."); var queue = new ConcurrentQueue <string>(); var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); var count = 0; var stop = false; var threads = Enumerable.Range(0, concurrency).Select(n => new Thread(() => { if ((n & 0x01) == 0) { var rand = new Random(); while (!stop) { queue.Enqueue(rand.Next().ToString()); } } else { while (!stop) { if (queue.TryDequeue(out var s)) { Interlocked.Increment(ref count); } } } })).ToArray(); Parallel.ForEach(threads, t => t.Start()); log($" warming up for 10 seconds"); Thread.Sleep(10_000); sw.Start(); Interlocked.Exchange(ref count, 0); log($" Measuring for 10 seconds"); Thread.Sleep(10_000); sw.Stop(); stop = true; Parallel.ForEach(threads, t => t.Join()); var rate = count / sw.Elapsed.TotalSeconds; log($"{nameof(ConcurrentQueueBench)} {count} enqueue/dequeue in {sw.Elapsed}. QPS={rate:G3}"); log($" Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}\n"); }
public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws <ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0 }
private static void StackBench(Action <string> log) { var stack = new Stack <string>(); var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); var totalCount = 20_000_000; sw.Start(); for (int i = 0; i < totalCount; i++) { stack.Push(i.ToString()); } while (stack.TryPop(out var s)) { } sw.Stop(); var rate = totalCount / sw.Elapsed.TotalSeconds; log($"{nameof(StackBench)} {totalCount} Push/Pop in {sw.Elapsed}. QPS={rate:G3}"); log($" Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}\n"); }
private static void StartInteractiveConsoleThread() { // Run the interaction on a separate thread as we don't have Console.KeyAvailable on .NET Core so can't // do a pre-emptive check before we call Console.ReadKey (which blocks, hard) var started = new ManualResetEvent(false); var interactiveThread = new Thread(() => { Console.WriteLine("Press 'C' to force GC or any other key to display GC stats"); Console.WriteLine(); started.Set(); while (true) { var key = Console.ReadKey(intercept: true); if (key.Key == ConsoleKey.C) { Console.WriteLine(); Console.Write("Forcing GC..."); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine(" done!"); } else { Console.WriteLine(); Console.WriteLine($"Allocated: {GetAllocatedMemory()}"); Console.WriteLine($"Gen 0: {GC.CollectionCount(0)}, Gen 1: {GC.CollectionCount(1)}, Gen 2: {GC.CollectionCount(2)}"); } } }) { IsBackground = true }; interactiveThread.Start(); started.WaitOne(); }
private static void DictionaryBench(Action <string> log) { var dict = new Dictionary <long, string>(); var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); var totalCount = 20_000_000; sw.Start(); for (int i = 0; i < totalCount; i++) { dict.Add(i, i.ToString()); } foreach (var kvp in dict) { if (kvp.Key.ToString() != kvp.Value) { throw new Exception(); } } for (int i = 0; i < totalCount; i++) { dict.Remove(i); } sw.Stop(); var rate = totalCount / sw.Elapsed.TotalSeconds; log($"{nameof(DictionaryBench)} {totalCount}Add/Query/Remove in {sw.Elapsed}. QPS={rate:G3}"); log($" Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}\n"); }
static void Main(string[] args) { if ((args.Length > 0) && (args.Length < 2)) { Console.WriteLine("Usage: Allocation.exe <maxbytes> <byteArraySize> "); return; } string processor = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); Console.WriteLine("Running on {0}", processor); UInt64 MaxBytes = 1500000000; if (processor.ToLower() == "amd64") { MaxBytes = 5000000000; } int byteArraySize = 95000; if (args.Length >= 2) { if (!UInt64.TryParse(args[0], out MaxBytes)) { Console.WriteLine("Usage: Allocation.exe <maxbytes> <byteArraySize> "); return; } if (!Int32.TryParse(args[1], out byteArraySize)) { Console.WriteLine("Usage: Allocation.exe <maxbytes> <byteArraySize> "); return; } } //check if running on server GC: if (!System.Runtime.GCSettings.IsServerGC) { Console.WriteLine("GCSettings is not server GC!"); return; } //Allocate memory UInt64 objCount = MaxBytes / (UInt64)byteArraySize; Console.WriteLine("Creating a list of {0} objects", objCount); if (objCount > 0X7FEFFFFF) { Console.WriteLine("Exceeded the max number of objects in a list"); Console.WriteLine("Creating a list with {0} objects", 0X7FEFFFFF); objCount = 0X7FEFFFFF; } Console.WriteLine("Byte array size is " + byteArraySize); Object[] objList = new Object[objCount]; long timerStart = Environment.TickCount; int count = (int)objCount; for (int i = 0; i < count; i++) { objList[i] = new byte[byteArraySize]; } long timerEnd = Environment.TickCount; long allocTime = timerEnd - timerStart; Console.WriteLine("Allocation time= {0} ms", allocTime); Console.WriteLine("GC count: "); Console.WriteLine("gen0: " + GC.CollectionCount(0)); Console.WriteLine("gen1: " + GC.CollectionCount(1)); Console.WriteLine("gen2: " + GC.CollectionCount(2)); }
private static void ConcurrentDictionaryBench(Action <string> log, int concurrency) { var dict = new ConcurrentDictionary <int, string>(); var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); var totalCount = 20_000_000 / concurrency; sw.Start(); var threads = Enumerable.Range(0, concurrency).Select(n => new Thread(() => { var begin = totalCount * n; var end = begin + totalCount; for (int i = begin; i < end; i++) { dict.TryAdd(i, i.ToString()); } foreach (var kvp in dict) { if (kvp.Key.ToString() != kvp.Value) { throw new Exception(); } } for (int i = begin; i < end; i++) { dict.Remove(i, out var s); } })).ToArray(); Parallel.ForEach(threads, t => t.Start()); Parallel.ForEach(threads, t => t.Join()); sw.Stop(); var rate = totalCount / sw.Elapsed.TotalSeconds; log($"{nameof(ConcurrentDictionaryBench)} {totalCount}Add/Query/Remove in {sw.Elapsed}. QPS={rate:G3}"); log($" Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}\n"); }