Created
March 21, 2020 01:20
-
-
Save samuelcarreira/dad1f819606b37022703713a16b0fa8b to your computer and use it in GitHub Desktop.
Benchmark time subtraction: process.hrtime; process.hrtime.bigint(); Date.now()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* I know that the process.hrtime as a higher precision over the | |
* Date constructor object so it's not a "fair" benchmark, | |
* but if you doesn't need a high precision timer and you just want | |
* to compare the fastest time subtraction this benchmark can | |
* be usefull | |
* | |
* Licensed under MIT | |
* Copyright (c) 2020 [Samuel Carreira] | |
*/ | |
const benchmark = require('nodemark'); | |
const os = require('os'); | |
function dateNow() { | |
const t = Date.now(); | |
return Date.now() - t; // milliseconds | |
} | |
function hrTimeBigInt() { | |
const t = process.hrtime.bigint(); | |
return process.hrtime.bigint() - t; // nanoseconds | |
} | |
function hrTime() { | |
const t = process.hrtime(); | |
const diff = process.hrtime(t); | |
return diff[0] * 1e9 + diff[1]; // nanoseconds | |
} | |
console.log(`Node ${process.version}`); | |
console.log(`CPU ${os.cpus()[0].model}`); | |
console.log('process.hrtime: ' + benchmark(hrTime)); | |
console.log('process.hrtime.bigint(): ' + benchmark(hrTimeBigInt)); | |
console.log('Date.now(): ' + benchmark(dateNow)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run 1:
Node v18.13.0
CPU Apple M1 Max
process.hrtime: 14,693,093 ops/sec ±0.42% (16188265 samples)
process.hrtime.bigint(): 12,370,171 ops/sec ±0.29% (16894424 samples)
Date.now(): 12,599,143 ops/sec ±0.33% (15674109 samples)
Run 2:
Node v18.13.0
CPU Apple M1 Max
process.hrtime: 14,652,087 ops/sec ±0.43% (16216034 samples)
process.hrtime.bigint(): 12,301,886 ops/sec ±0.28% (16976581 samples)
Date.now(): 12,799,446 ops/sec ±0.31% (15855477 samples)
Interesting results.