You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用Hermes引擎时如何测量函数调用的耗时性能

Hermes引擎下函数耗时统计解决方案

报错原因

Hermes引擎在非调试的真机运行环境下,未默认实现console.time、console.timeEnd和performance.now等API,Chrome调试模式下JS代码运行在V8引擎中,因此可以正常调用上述API。

方案1:基于Date.now封装兼容版计时工具

Date.now在所有版本Hermes中都可以正常使用,兼容性最好,适合大多数常规耗时统计场景:

// 全局存储计时标记
const timeMarkers = {}

// 模拟console.time功能
const customTime = (label) => {
  timeMarkers[label] = Date.now()
}

// 模拟console.timeEnd功能,打印并返回耗时
const customTimeEnd = (label) => {
  if (!timeMarkers[label]) {
    console.warn(`计时标记 ${label} 不存在`)
    return
  }
  const duration = Date.now() - timeMarkers[label]
  console.log(`${label}: ${duration}ms`)
  delete timeMarkers[label]
  return duration
}

替换原有业务代码即可:

const checkTime = () => {
  customTime('time_NoOp')
  doNothing()
  customTimeEnd('time_NoOp')
}

方案2:基于Hermes内置API实现高精度计时

如果需要微秒级的高精度统计,可以使用Hermes内置的hermes.internal.now()API,返回带小数位的毫秒数,精度远高于Date.now:

const highPrecisionMarkers = {}

const highPrecisionTime = (label) => {
  // 兼容不存在Hermes内置API的场景
  highPrecisionMarkers[label] = global.hermes?.internal?.now() || Date.now()
}

const highPrecisionTimeEnd = (label) => {
  if (!highPrecisionMarkers[label]) {
    console.warn(`计时标记 ${label} 不存在`)
    return
  }
  const end = global.hermes?.internal?.now() || Date.now()
  const duration = (end - highPrecisionMarkers[label]).toFixed(2)
  console.log(`${label}: ${duration}ms`)
  delete highPrecisionMarkers[label]
  return duration
}

补充说明

  • React Native 0.70及以上版本的Hermes引擎已经原生支持performance.nowAPI,升级版本后可以直接使用该API实现高精度计时
  • 生产环境建议关闭计时逻辑,避免额外的性能开销,同时不要在release包中保留console输出
  • 如果需要批量分析函数耗时,可以配合React Native自带的性能分析工具Flipper的Hermes Profiler插件使用

内容的提问来源于stack exchange,提问作者rahul goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:24:06