8、.NET Core 實踐 2024-03-29 11:44 CPU過高

Windbg 指令記錄

0:008> !runaway
 User Mode Time
  Thread       Time
    7:35c0     0 days 0:03:04.953
    8:111c     0 days 0:03:01.640
    6:4d30     0 days 0:02:57.281
    5:8424     0 days 0:02:52.640
    0:6fe8     0 days 0:00:00.031
    2:6c28     0 days 0:00:00.015
    4:6430     0 days 0:00:00.000
    3:7188     0 days 0:00:00.000
    1:4d0      0 days 0:00:00.000
0:008> ~8
.  8  Id: 6b50.111c Suspend: 0 Teb: 000000d0`f1d77000 Unfrozen
      Start: coreclr!Thread::intermediateThreadProc (00007ffb`e0c63440)
      Priority: 0  Priority class: 32  Affinity: fff
0:008> !clrstack
OS Thread Id: 0x111c (8)
        Child SP               IP Call Site
000000D0F2E7EDA0 00007ffb8117631b Sx.WinDbg.Program.StressCPU()
000000D0F2E7EE30 00007ffbe04a20eb System.Threading.ThreadHelper.ThreadStart_Context(System.Object) [/_/src/System.Private.CoreLib/src/System/Threading/Thread.CoreCLR.cs @ 44]
000000D0F2E7EE60 00007ffbe0499296 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [/_/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @ 172]
000000D0F2E7EEE0 00007ffbe048553b System.Threading.ThreadHelper.ThreadStart() [/_/src/System.Private.CoreLib/src/System/Threading/Thread.CoreCLR.cs @ 93]
000000D0F2E7F0F8 00007ffbe0c76ca3 [GCFrame: 000000d0f2e7f0f8] 
000000D0F2E7F360 00007ffbe0c76ca3 [DebuggerU2MCatchHandlerFrame: 000000d0f2e7f360] 

對應的測試代碼

using System;
using System.Diagnostics;
using System.Threading;

namespace Sx.WinDbg
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CPU Stress Test");
            int numThreads = 4; // 可以根據需要調整線程數
            Thread[] threads = new Thread[numThreads];

            for (int i = 0; i < numThreads; i++)
            {
                threads[i] = new Thread(new ThreadStart(ThreadMatch.StressCPU));
                threads[i].Start();
            }

            Console.ReadLine(); // 等待輸入以防止程序立即退出
        }

       
    }
}

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace Sx.WinDbg
{
    internal class ThreadMatch
    {
        internal static void StressCPU()
        {
            double result = 0;
            Stopwatch sw = new Stopwatch();

            while (true)
            {
                sw.Start();
                for (int i = 0; i < 1000000; i++)
                {
                    result += Math.Sqrt(i);
                }
                sw.Stop();

                // 大約計算1秒鐘,以保持大約100%的CPU使用率
                if (sw.ElapsedMilliseconds < 1000)
                {
                    Thread.Sleep(1000 - (int)sw.ElapsedMilliseconds);
                }
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章