Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo [링크 복사], [링크+제목 복사],
조회: 14726
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

.NET 5+부터 지원되는 GC.GetGCMemoryInfo

아래와 같은 글에서 GetGCMemoryInfo에 대해 소개하고 있는데요,

The updated GetGCMemoryInfo API in .NET 5.0 and how it can help you
; https://devblogs.microsoft.com/dotnet/the-updated-getgcmemoryinfo-api-in-net-5-0-and-how-it-can-help-you/

.NET 3.0부터 BCL에 포함시켜둔 GC.GetGCMemoryInfo를 5.0부터 기능을 좀 더 보강했다고 합니다.

우선, .NET 3.0의 경우 GC.GetGCMemoryInfo가 반환한 GCMemoryInfo 타입은 아래의 기능만 가지고 있습니다.

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var buffer = new byte[4096];
            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);

            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);
        }

        static void CallGC()
        {
            GC.Collect(2, GCCollectionMode.Forced, true);
        }

        static void ShowGCInfo()
        {
            var info = GC.GetGCMemoryInfo();

            Console.WriteLine($"HeapSizeBytes: {info.HeapSizeBytes}, {GC.GetTotalMemory(false)}");
            Console.WriteLine($"TotalAvailableMemoryBytes: {info.TotalAvailableMemoryBytes}");
            Console.WriteLine($"FragmentedBytes: {info.FragmentedBytes}");
            Console.WriteLine($"HighMemoryLoadThresholdBytes: {info.HighMemoryLoadThresholdBytes}");
            Console.WriteLine($"MemoryLoadBytes: {info.MemoryLoadBytes}");

        }
    }
}

/* 출력 결과
HeapSizeBytes: 66168, 72928
TotalAvailableMemoryBytes: 67968360448
FragmentedBytes: 1432
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 55054371962


HeapSizeBytes: 81432, 84560
TotalAvailableMemoryBytes: 67968360448
FragmentedBytes: 2584
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 55054371962
*/

한 가지 유의할 점은, GetGCMemoryInfo는 마지막 GC 이후의 상황을 보여주는 것이므로 반드시 GC가 한 번 이상은 되어야 합니다.

하나씩 값을 살펴볼까요? ^^ 우선 HeapSizeBytes는 마지막 GC 이후 사용 중인 총 Heap의 크기를 의미합니다. 사실 이와 유사한 값을 반환하는 메서드가 GC.GetTotalMemory인데, 값이 살짝 다른 것을 볼 수 있습니다. 어느 것을 신뢰해야 할지 모르겠군요. ^^

그다음 TotalAvailableMemoryBytes는 지난 예제에서 다룬 것처럼,

C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
; https://www.sysnet.pe.kr/2/0/13146

프로세스가 사용할 수 있는 총 메모리 크기를 가져옵니다. 따라서 GCHeapHardLimit가 설정됐다면 그것을 반영한 값이 나옵니다. 보통은 일반적인 환경에서 물리 메모리에 가까운 값을 반환하므로, 크게 의미는 없습니다.

FragmentedBytes는 문서에 자세하게 설명이 나오므로 그것을 참조하시고... 역시나 GC Heap의 상황을 나타내는 것이므로 특별한 사유가 아니라면 역시 일반적인 성능 모니터링 상황에서는 눈여겨 보게 될 수치는 아닙니다.

HighMemoryLoadThresholdBytes는 GC가 좀 더 적극적으로 Full GC를 수행하는 임곗값이 됩니다. 따라서 정말 물리 메모리가 숨넘어가는 상황이 발생해 성능 저하가 발생하고 있는지를 판단할 수 있는 값이 되는데요, 꽤나 의미가 있어 보입니다. 그러니까, 현재 시스템 메모리의 사용량이 HighMemoryLoadThresholdBytes를 넘게 되면 일종의 경고 상황이 발생하는 것과 마찬가지라고 보면 되겠습니다.

마지막으로, MemoryLoadBytes는 MEMORYSTATUS structure의 dwMemoryLoad 필드 값에 해당한다고 합니다. 따라서 현재 물리 메모리의 사용률 정도로 여기면 되겠습니다.




자, 그럼 .NET 5 이후부터 추가된 멤버를 살펴볼까요? ^^ 대충 예제 코드는 이렇게 확장할 수 있습니다.

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var buffer = new byte[4096];
            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);

            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);

            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);

            buffer = new byte[4096];

            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);

        }

        static void CallGC()
        {
            GC.Collect(2, GCCollectionMode.Forced, true);
        }

        static void ShowGCInfo()
        { 
            var info = GC.GetGCMemoryInfo(GCKind.Any);

            /*
private GCGenerationInfo _generationInfo0; // Gen 0
private GCGenerationInfo _generationInfo1; // Gen 1
private GCGenerationInfo _generationInfo2; // Gen 2
private GCGenerationInfo _generationInfo3; // LOH
private GCGenerationInfo _generationInfo4; // POH
            */

            long totalAfter = 0;
            long totalBefore = 0;
            foreach (var ginfo in info.GenerationInfo)
            {
                Console.WriteLine($"{ginfo.SizeAfterBytes} {ginfo.SizeBeforeBytes}, {ginfo.FragmentationAfterBytes} {ginfo.FragmentationBeforeBytes}");
                totalAfter += ginfo.SizeAfterBytes;
                totalBefore += ginfo.SizeBeforeBytes;
            }

            Console.WriteLine($"HeapSizeBytes: {info.HeapSizeBytes}, {GC.GetTotalMemory(false)}, GenInfo After == {totalAfter}, Before == {totalBefore}");
            Console.WriteLine($"TotalCommittedBytes: {info.TotalCommittedBytes}");
            Console.WriteLine($"Generation: {info.Generation}");
            Console.WriteLine($"TotalAvailableMemoryBytes: {info.TotalAvailableMemoryBytes}");
            Console.WriteLine($"FinalizationPendingCount: {info.FinalizationPendingCount}");
            Console.WriteLine($"Concurrent: {info.Concurrent}");
            Console.WriteLine($"Compacted: {info.Compacted}");
            Console.WriteLine($"Index: {info.Index}");
            Console.WriteLine($"FragmentedBytes: {info.FragmentedBytes}");
            Console.WriteLine($"HighMemoryLoadThresholdBytes: {info.HighMemoryLoadThresholdBytes}");
            Console.WriteLine($"MemoryLoadBytes: {info.MemoryLoadBytes}");

            foreach (var duration in info.PauseDurations)
            {
                Console.WriteLine($"{duration.TotalMilliseconds}, {duration.Ticks}");
            }

            Console.WriteLine($"PauseTimePercentage: {info.PauseTimePercentage}");
            Console.WriteLine($"PinnedObjectsCount: {info.PinnedObjectsCount}");
            Console.WriteLine($"PromotedBytes: {info.PromotedBytes}");
        }
    }
}

실행해 보면,

24 82048, 0 11640
82072 24, 15648 0
24 24, 0 0
24 24, 0 0
17440 17440, 0 0
HeapSizeBytes: 99584, 118776, GenInfo After == 99584, Before == 99560
TotalCommittedBytes: 221184
Generation: 2
TotalAvailableMemoryBytes: 67968360448
FinalizationPendingCount: 2
Concurrent: False
Compacted: False
Index: 1
FragmentedBytes: 15648
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 51655953940
0.706, 7060
0, 0
PauseTimePercentage: 2.78
PinnedObjectsCount: 1
PromotedBytes: 84128


48 147472, 0 37736
147496 82096, 46088 15648
82120 48, 16128 0
48 48, 0 0
53296 53296, 0 0
HeapSizeBytes: 183424, 153240, GenInfo After == 283008, Before == 282960
TotalCommittedBytes: 286720
Generation: 2
TotalAvailableMemoryBytes: 67968360448
FinalizationPendingCount: 2
Concurrent: False
Compacted: False
Index: 2
FragmentedBytes: 46568
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 51655953940
0.163, 1630
0, 0
PauseTimePercentage: 2.54
PinnedObjectsCount: 1
PromotedBytes: 137120


72 173592, 0 47536
173568 147520, 61952 46088
229640 82144, 62664 16128
72 72, 0 0
89152 89152, 0 0
HeapSizeBytes: 209496, 171672, GenInfo After == 492504, Before == 492480
TotalCommittedBytes: 286720
Generation: 2
TotalAvailableMemoryBytes: 67968360448
FinalizationPendingCount: 4
Concurrent: False
Compacted: False
Index: 3
FragmentedBytes: 62400
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 51655953940
0.163, 1630
0, 0
PauseTimePercentage: 2.54
PinnedObjectsCount: 1
PromotedBytes: 147168


96 219856, 0 75208
219832 173592, 94736 61952
403232 229664, 126056 62664
96 96, 0 0
125008 125008, 0 0
HeapSizeBytes: 255760, 184160, GenInfo After == 748264, Before == 748216
TotalCommittedBytes: 352256
Generation: 2
TotalAvailableMemoryBytes: 67968360448
FinalizationPendingCount: 3
Concurrent: False
Compacted: False
Index: 4
FragmentedBytes: 96176
HighMemoryLoadThresholdBytes: 61171524403
MemoryLoadBytes: 51655953940
0.186, 1860
0, 0
PauseTimePercentage: 2.59
PinnedObjectsCount: 1
PromotedBytes: 159608

다른 건 크게 관심이 없고, 세대별 GC Heap의 크기를 알 수 있는 GenerationInfo가 눈에 띄는데요,

long totalAfter = 0;
long totalBefore = 0;
foreach (var ginfo in info.GenerationInfo)
{
    Console.WriteLine($"{ginfo.SizeAfterBytes} {ginfo.SizeBeforeBytes}, {ginfo.FragmentationAfterBytes} {ginfo.FragmentationBeforeBytes}");
    totalAfter += ginfo.SizeAfterBytes;
    totalBefore += ginfo.SizeBeforeBytes;
}

이에 대한 출력 결과는 5개가 나옵니다.

96 219856, 0 75208
219832 173592, 94736 61952
403232 229664, 126056 62664
96 96, 0 0
125008 125008, 0 0

왜냐하면, 차례대로 Gen0, Gen1, Gen2의 정보와 함께 이후 LOH, POH의 정보를 보여주기 때문입니다.

그런데, 각각의 세대에 해당하는 SizeAfterBytes 정보가 해석이 잘 안 됩니다. 그냥 문서상으로는 GC 이후 해당 Gen에 남아 있는 바이트를 의미하는데요, 그렇다면 그 값들을 모두 더한 경우 HeapSizeBytes와 (적어도) 비슷한 정도는 돼야 합니다.

HeapSizeBytes: 255760, 184160, GenInfo After == 748264, Before == 748216

아쉽게도 보는 바와 같이, SizeAfter의 총 크기가 748264인 반면, HeapSizeBytes는 255760에 불과합니다. 여기서 재미있는 건, 처음 2번의 GC에서는 HeapSizeBytes와 SizeAfter가 값이 동일했다는 점입니다. 오호~~~ 이걸 어떻게 해석해야 할지 모르겠군요. ^^ 그러다 혹시나 싶어 .NET 7 런타임에서 해당 코드를 실행했더니,

...[이전 출력 생략]...

0 24544, 0 17968
24544 19584, 20416 12568
174392 154872, 64512 52000
0 0, 0 0
35832 35832, 0 0
HeapSizeBytes: 234768, 162072, GenInfo After == 234768, Before == 234832
...[생략]...

정확히 일치합니다. 아쉽지만, 저 값을 각 세대별 Heap 사용량으로 쓰려면 .NET 7까지 기다려야 할 듯합니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/2/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12361정성태10/11/202019632.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/202014901오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/202017108오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/202017938오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/202015585오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202031228오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/202014752오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202028721오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202018216개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202019431개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202017916오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202022341Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/202016494Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/202017562오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202033100Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/202016555오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/202016035오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/202017975Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
12343정성태9/24/202029043.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202019082디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
12341정성태9/23/202017124.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/202016780.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/202016959오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/202016952오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202018057오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202021470.NET Framework: 942. C# - WOL(Wake On Lan) 구현
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...