跳到主要内容

CpuMetrics

数据结构

字节索引类型字段含义
0-3float32CPU 使用率 [%]
4-7float32CPU 频率 [MHz]
8-11float32CPU 温度 [℃]
12-13uint16CPU 核心数量
14-15uint16保留字段,必须为 0
16-(16+8×N1)(16+8 \times N-1)CpuCoreMetrics 数组CPU 单核指标数组,N 为核心数

单个 CpuCoreMetrics 固定为 8 字节,因此总长度为 16+core_count×816 + core\_count \times 8 字节

示例

C++ 示例
struct CpuCoreMetrics {
float usage;
float frequency;
};

struct CpuMetricsHeader {
float usage;
float frequency;
float temperature;
uint16_t core_count;
uint16_t reserved;
};

// payload = CpuMetricsHeader + core_count * CpuCoreMetrics
Rust 示例
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct CpuCoreMetrics {
pub usage: f32,
pub frequency: f32,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct CpuMetricsHeader {
pub usage: f32,
pub frequency: f32,
pub temperature: f32,
pub core_count: u16,
pub reserved: u16,
}

const _: () = {
assert!(core::mem::size_of::<CpuCoreMetrics>() == 8);
assert!(core::mem::size_of::<CpuMetricsHeader>() == 16);
};

Dart 示例
import 'dart:typed_data';

final class CpuMetricsView {
static const int headerLength = 16;
static const int coreMetricsLength = 8;

final ByteBuffer buffer;
final ByteData header;
final int offsetInBytes;

CpuMetricsView(this.buffer, [this.offsetInBytes = 0])
: header = ByteData.view(buffer, offsetInBytes, headerLength);

double get usage => header.getFloat32(0, Endian.little);
double get frequency => header.getFloat32(4, Endian.little);
double get temperature => header.getFloat32(8, Endian.little);
int get coreCount => header.getUint16(12, Endian.little);
int get byteLength => headerLength + coreCount * coreMetricsLength;

ByteData coreMetricsData(int index) {
return ByteData.view(
buffer,
offsetInBytes + headerLength + index * coreMetricsLength,
coreMetricsLength,
);
}
}

Java 示例
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public final class CpuMetricsView {
public static final int HEADER_LENGTH = 16;
public static final int CORE_METRICS_LENGTH = 8;

private final ByteBuffer buffer;
private final int offset;

public CpuMetricsView(ByteBuffer buffer, int offset) {
this.buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
this.offset = offset;
}

public float usage() { return buffer.getFloat(offset); }
public float frequency() { return buffer.getFloat(offset + 4); }
public float temperature() { return buffer.getFloat(offset + 8); }
public int coreCount() { return Short.toUnsignedInt(buffer.getShort(offset + 12)); }
public int byteLength() { return HEADER_LENGTH + coreCount() * CORE_METRICS_LENGTH; }

public int coreMetricsOffset(int index) {
return offset + HEADER_LENGTH + index * CORE_METRICS_LENGTH;
}
}