如何找到此函数执行多少时间?

export async function queryElasticSearch(userQuery, index) {
    if (_.isEmpty(userQuery)) {
        throw new Error('User query is empty or null');
    }
    try {
        const elasticSearchRequestBody = getElasticSearchRequestBody(index, userQuery);
        return await elasticSearchClient.search(elasticSearchRequestBody);
    } catch (err) {
        throw err;
    }
}

最佳答案

像这样:

export async function queryElasticSearch(userQuery, index) {
  const start = Date.now()
  try {
    if (_.isEmpty(userQuery)) throw new Error('User query is empty or null');
    const elasticSearchRequestBody = getElasticSearchRequestBody(index, userQuery);
    return await elasticSearchClient.search(elasticSearchRequestBody);
  } finally {
    console.log(Date.now() - start)
  }
}


或者,如果您希望以微秒为单位的精度,则可以使用performance.now()。

编辑:最后根据Bergi建议添加。

09-25 19:38