Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
56 lines
2.3 KiB
C++
56 lines
2.3 KiB
C++
// Shared helpers for the model-free roofline microbenchmarks (docs/roofline.md).
|
|
// Every program prints "RESULT <name> key=value ..." lines so the numbers can be grepped into the docs.
|
|
#pragma once
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
static inline double now_s() {
|
|
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
|
}
|
|
|
|
// MemAvailable in bytes (Linux); 0 when unknown.
|
|
static inline uint64_t mem_available_bytes() {
|
|
FILE* f = std::fopen("/proc/meminfo", "r");
|
|
if (!f) return 0;
|
|
char line[256];
|
|
unsigned long kb = 0;
|
|
while (std::fgets(line, sizeof line, f))
|
|
if (std::sscanf(line, "MemAvailable: %lu kB", &kb) == 1) break;
|
|
std::fclose(f);
|
|
return (uint64_t)kb * 1024;
|
|
}
|
|
|
|
// The server rule: never let MemAvailable drop below the reserve (default 15 GiB, MB_RESERVE_GIB overrides).
|
|
static inline bool host_alloc_allowed(uint64_t bytes) {
|
|
const char* e = std::getenv("MB_RESERVE_GIB");
|
|
const uint64_t reserve = (uint64_t)((e ? std::atof(e) : 15.0) * (1ull << 30));
|
|
const uint64_t avail = mem_available_bytes();
|
|
if (avail != 0 && avail < bytes + reserve) {
|
|
std::fprintf(stderr, "refusing to allocate %.1f GiB: MemAvailable %.1f GiB, reserve %.1f GiB\n",
|
|
bytes / 1073741824.0, avail / 1073741824.0, reserve / 1073741824.0);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static inline double median(std::vector<double> v) {
|
|
std::sort(v.begin(), v.end());
|
|
return v.empty() ? 0.0 : v[v.size() / 2];
|
|
}
|
|
static inline double pct(std::vector<double> v, double p) {
|
|
std::sort(v.begin(), v.end());
|
|
if (v.empty()) return 0.0;
|
|
size_t i = (size_t)(p * (v.size() - 1) + 0.5);
|
|
return v[i];
|
|
}
|
|
|
|
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, "CUDA error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, cudaGetErrorString(e_)); std::exit(2); } } while (0)
|
|
// A failure that should not abort the whole sweep (an unsupported registration kind, say).
|
|
#define CKS(x) ([&]() { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, " (skipped: %s: %s)\n", #x, cudaGetErrorString(e_)); (void)cudaGetLastError(); return false; } return true; }())
|