これが私が使用するものです。JavaScript であるため、Frontend と node.js の両方のソリューションを投稿します。
どちらの場合も、同じ小数丸め関数を使用します。理由は次のとおりです。
const round = (places, number) => +(Math.round(number + `e+${places}`) + `e-${places}`)
places
- 丸める小数点以下の桁数。これは安全であり、浮動小数点数の問題を回避する必要があります (1.0000000000005~ のような数値は問題になる可能性があります)。ミリ秒に変換された高解像度タイマーによって提供される小数を丸める最良の方法を研究するのに時間を費やしました。
that + symbol
- オペランドを数値に変換する単項演算子です。Number()
ブラウザ
const start = performance.now()
// I wonder how long this comment takes to parse
const end = performance.now()
const result = (end - start) + ' ms'
const adjusted = round(2, result) // see above rounding function
node.js
// Start timer
const startTimer = () => process.hrtime()
// End timer
const endTimer = (time) => {
const diff = process.hrtime(time)
const NS_PER_SEC = 1e9
const result = (diff[0] * NS_PER_SEC + diff[1])
const elapsed = Math.round((result * 0.0000010))
return elapsed
}
// This end timer converts the number from nanoseconds into milliseconds;
// you can find the nanosecond version if you need some seriously high-resolution timers.
const start = startTimer()
// I wonder how long this comment takes to parse
const end = endTimer(start)
console.log(end + ' ms')