Example: VulkanExamples/p42_budget
Post 42 in the series (post 28: capability queries, post: memory types).
VkPhysicalDeviceMemoryProperties 告诉你堆大小——包装盒上印的 16GB。它不告诉你:堆已经用掉多少(别的应用、合成器、你自己的早期分配),以及驱动愿意给你多少。VK_EXT_memory_budget 用一个链入 struct 补上两个缺口:
main.cpp (excerpt)
vk::PhysicalDeviceMemoryBudgetPropertiesEXT budget{};
vk::PhysicalDeviceMemoryProperties2 mp{};
mp.pNext = &budget;
phys.getMemoryProperties2(&mp);
for (uint32_t i = 0; i < mp.memoryProperties.memoryHeapCount; ++i)
printf("heap%u size=%lluMB usage=%lluMB budget=%lluMB\n", i,
(unsigned long long)(mp.memoryProperties
.memoryHeaps[i].size >> 20),
(unsigned long long)(budget.heapUsage[i] >> 20),
(unsigned long long)(budget.heapBudget[i] >> 20));heapBudget[i]——驱动当前允许你分配的量(堆大小减去驱动保留减去其他进程)。heapUsage[i]——此刻实际已分配的量。
测试 Radeon 上:
example.sh
--- before allocations ---
heap0 size=16128MB usage=0MB budget=15124MB flags=0x1 # VRAM
heap1 size=15540MB usage=0MB budget=15339MB flags=0x0 # GTT/host
heap2 size=256MB usage=0MB budget=54MB flags=0x1 # BAR carve-out
--- after 3x256MB device-local ---
heap0 size=16128MB usage=768MB budget=15124MB flags=0x1
两个有启发的细节:
- budget ≠ size:heap0 的 16GB 只有 15.1GB 预算——驱动给自己留 ~1GB(页表、固件、其他客户端)。heap2 是 resizable-BAR 窗口:256MB 的堆只有 54MB 预算,即大头被永久保留。
- usage 算的不只是你:共享堆上
heapUsage是全系统的——别的应用分配 VRAM 也在这里出现,这正是应用在驱逐或扩张缓存时该重查预算、而不是信堆大小的原因。
校验
check.py
# SPDX-License-Identifier: CC0-1.0
import re, subprocess
o = subprocess.run(["./app"], check=True, capture_output=True,
text=True).stdout
def parse(text):
return {i: (int(u), int(b)) for i, u, b in re.findall(
r"heap(\d+) size=\d+MB usage=(\d+)MB budget=(\d+)MB "
r"flags=0x1", text)}
before, _, after = o.partition("--- after 3x256MB device-local ---")
heaps_b = parse(before)
heaps_a = parse(after)
assert heaps_b and heaps_a, o
grew = [i for i in heaps_a
if heaps_a[i][0] - heaps_b.get(i, (0, 0))[0] >= 700]
assert grew, f"no heap grew by ~768MB: {o}"
print("OK: heap budget/usage reported, device-local usage +768MB")example.sh
$ python3 check.py
OK: heap budget/usage reported, device-local usage +768MB
不该怎么用
- 别把 budget 当承诺——查询和
vkAllocateMemory之间它可能缩水(别的应用抢了内存)。eOutOfDeviceMemory仍要处理;预算是策略输入,不是预留。 - 别把各堆预算相加——堆之间以奇怪方式重叠(BAR 堆是 VRAM 的窗口);按 flag 选对的堆。
- 别每帧重查——这是近乎系统调用的查询;按分配压力或定时器轮询,别逐 draw。
本系列所有源代码以 CC0 1.0 Universal(CC0-1.0) 发布——公有领域奉献,无需署名。