Skip to content
systemcoding.dev
GPU

Get the GPU with MTLCreateSystemDefaultDevice

Get the default Metal GPU with MTLCreateSystemDefaultDevice in Objective-C on macOS 14 and read its name, unified memory flag and working-set budget.

1 min read
Summarize in AI

Every Metal program starts with a device object, and MTLCreateSystemDefaultDevice() returns the one the system prefers. On a laptop with two GPUs that is usually the integrated one, so do not assume it is the fastest. This is Objective-C on macOS 14 with the Xcode 15 SDK.

device.mobjc
#import <Metal/Metal.h>
#import <Foundation/Foundation.h>

int main(void)
{
    @autoreleasepool {
        id<MTLDevice> device = MTLCreateSystemDefaultDevice();
        if (!device) {
            NSLog(@"no Metal device");
            return 1;
        }
        NSLog(@"name: %@", device.name);
        NSLog(@"unified memory: %@", device.hasUnifiedMemory ? @"yes" : @"no");
        NSLog(@"working set: %llu MiB",
              device.recommendedMaxWorkingSetSize >> 20);
    }
    return 0;
}
Text
name: Apple M2
unified memory: yes
working set: 10922 MiB

The name and the working-set figure depend on the machine; the values shown are an example for a 16 GB Apple silicon Mac. hasUnifiedMemory tells you whether CPU and GPU share one pool, which decides whether you need managed or private storage modes later. recommendedMaxWorkingSetSize is the documented budget before the system starts evicting resources, and it is a recommendation, not a hard cap. See MTLCreateSystemDefaultDevice.

To pick a specific GPU on a multi-GPU Mac, call MTLCopyAllDevices() instead and choose by isLowPower or isRemovable. The function returns nil inside some virtual machines and on very old hardware, so check it. Compile with clang -framework Metal -framework Foundation device.m.

Share

More snippets

GPU

List platforms with clGetPlatformIDs

Call clGetPlatformIDs twice, once for the count and once for the handles, then print each platform name with clGetPlatformInfo in OpenCL 3.0 C.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.