概述
SDK 提供监控沙箱资源使用情况的功能,包括 CPU、内存和磁盘使用量。指标每 5 秒收集一次。
获取指标
从活动沙箱实例获取
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sbx = await Sandbox.create()
// Wait for metrics to be collected
await new Promise(resolve => setTimeout(resolve, 6000))
const metrics = await sbx.getMetrics()
// You can also get the metrics by sandbox ID:
// const metrics = await Sandbox.getMetrics(sbx.sandboxId)
console.log('Sandbox metrics:', metrics)
// Sandbox metrics:
// [
// {
// timestamp: 2025-07-28T08:04:05.000Z,
// cpuUsedPct: 20.33,
// cpuCount: 2,
// memUsed: 32681984, // in bytes
// memTotal: 507592704, // in bytes
// diskUsed: 1514856448, // in bytes
// diskTotal: 2573185024 // in bytes
// },
// {
// timestamp: 2025-07-28T08:04:10.000Z,
// cpuUsedPct: 0.2,
// cpuCount: 2,
// memUsed: 33316864, // in bytes
// memTotal: 507592704, // in bytes
// diskUsed: 1514856448, // in bytes
// diskTotal: 2573185024 // in bytes
// }
// ]
await sbx.kill()
}
main()
使用沙箱 ID 获取
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sandboxId = 'your-sandbox-id'
const metrics = await Sandbox.getMetrics(sandboxId)
console.log(metrics)
}
main()
指标数据结构
指标返回一个数组,每个元素包含一次采样的资源使用情况:
| 字段 | 类型 | 说明 |
|---|---|---|
timestamp |
Date | 采样时间戳 |
cpuUsedPct |
number | CPU 使用百分比 |
cpuCount |
number | CPU 核心数 |
memUsed |
number | 已使用内存(字节) |
memTotal |
number | 总内存(字节) |
diskUsed |
number | 已使用磁盘空间(字节) |
diskTotal |
number | 总磁盘空间(字节) |
重要注意事项
首次指标延迟:沙箱创建后可能需要 1 秒或更长时间才能收集到第一批指标。在此之前,getMetrics() 返回空数组。建议在沙箱创建后等待至少 5-6 秒再获取指标。
最佳实践
- 等待首次采样:创建沙箱后等待至少 6 秒再获取指标
- 定期轮询:每 5 秒或更长间隔获取指标
- 资源告警:设置阈值监控资源使用,及时发现问题
- 性能优化:使用指标数据优化代码和资源配置
文档反馈
(如有产品使用问题,请 提交工单)