How to get VRAM usage via C++

Hi, is it possible to get the current VRAM usage in C++? Through RHI or something?

I attached an example screenshot of what I want to achieve. Thanks in advance.

Surprised it took 5 years for someone to figure this out, but hereā€™s how you do it. This will allow you to retrieve used, available, and total VRAM figures, but only on Windows.

  1. Create a new gameplay module. You can follow the guide in the Unreal Docs here.
  2. The new module should have the following *.Build.cs file contents:
using UnrealBuildTool;

public class LowLevelTelemetry : ModuleRules {
  public LowLevelTelemetry(ReadOnlyTargetRules Target) : base(Target) {
    PrivateDependencyModuleNames.AddRange(new string[] {
      "Core",
      "CoreUObject",
      "Engine"
    });

    PublicIncludePathModuleNames.AddRange(new string[] { "RHI" });

    if ((Target.IsInPlatformGroup(UnrealPlatformGroup.Windows)))
    {
      // Uses DXGI to query GPU hardware
      // This is what will allow us to get GPU usage statistics at runtime
      PublicSystemLibraries.Add("DXGI.lib");
    }
  }
}
  1. In the moduleā€™s main header file, add the following includes:
#include <CoreMinimal.h>
#include "Windows/WindowsHWrapper.h"

THIRD_PARTY_INCLUDES_START
#include "Windows/AllowWindowsPlatformTypes.h"
#include "Windows/PreWindowsApi.h"
#include "dxgi1_4.h"
#include "Windows/PostWindowsApi.h"
#include "Windows/HideWindowsPlatformTypes.h"
THIRD_PARTY_INCLUDES_END
  1. Now for the implementations:
static size_t GetUsedVideoMemory() {
    IDXGIFactory4* pFactory;
    CreateDXGIFactory1(__uuidof(IDXGIFactory4), (void**)&pFactory);

    IDXGIAdapter3* adapter;
    pFactory->EnumAdapters(0, reinterpret_cast<IDXGIAdapter**>(&adapter));

    DXGI_QUERY_VIDEO_MEMORY_INFO videoMemoryInfo;
    adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &videoMemoryInfo);

    size_t usedVRAM = videoMemoryInfo.CurrentUsage / 1024 / 1024;

    return usedVRAM;
}

You can get

videoMemoryInfo.AvailableForReservation

and

videoMemoryInfo.Budget

to get available and total VRAM as well.

  1. Add the new module as a dependency to your game module (YourGame.Build.cs):
PrivateDependencyModuleNames.AddRange(new string[] {
    "YourNewModule"
});

Thatā€™s it, tested and working in 5.1. Hope that helps!

References:

5 Likes

Hi!

Thanks for the sharing. Iā€™m having some issues and would like to consult you about this error.

Error : Unable to find ā€˜classā€™, ā€˜delegateā€™, ā€˜enumā€™, or ā€˜structā€™ with name ā€˜size_tā€™

I tried to ā€œincludeā€ but none works.

image

Any idea?

You canā€™t have UPROPERTY of just any type, only those that are supported explicitly by the engine (int, bool, float, etc) and those that use the various engine macros (USTRUCT , UCLASS, etc).

size_t is neither. If you want a UPROPERTY, youā€™ll have to choose from something more explicit like int, int32, int64, uint32, etc.

1 Like

Thanks! int32 is worked.