Repository URL to install this package:
|
Version:
0.0.5 ▾
|
type HighResolutionTime = [number, number]
// Converts an hrtime array (as returned from process.hrtime) to nanoseconds.
//
// ONLY CALL THIS ON VALUES REPRESENTING DELTAS, NOT ON THE RAW RETURN VALUE
// FROM process.hrtime() WITH NO ARGUMENTS.
//
// The entire point of the hrtime data structure is that the JavaScript Number
// type can't represent all int64 values without loss of precision:
// Number.MAX_SAFE_INTEGER nanoseconds is about 104 days. Calling this function
// on a duration that represents a value less than 104 days is fine. Calling
// this function on an absolute time (which is generally roughly time since
// system boot) is not a good idea.
function durationHrTimeToNanos(hrtimeList: HighResolutionTime) {
return hrtimeList[0] * 1e9 + hrtimeList[1]
}
const IS_BROWSER = typeof window === 'object'
// global.performance = require('perf_hooks'), (global as any).performance.now
// (time?: [number, number]) => [window.performance.now]
const performanceNow = IS_BROWSER ? window.performance.now : process.hrtime
/**
* @description generate timestamp or delta
* @see http://nodejs.org/api/process.html#process_process_hrtime
*/
function hrtimeBrowser(previousTimestamp?: HighResolutionTime): HighResolutionTime {
const clockTime = performanceNow.call(performance) * 1e-3
let seconds = Math.floor(clockTime)
let nanoseconds = Math.floor((clockTime % 1) *1e9)
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0]
nanoseconds = nanoseconds - previousTimestamp[1]
if (nanoseconds < 0) {
seconds--
nanoseconds += 1e9
}
}
return [seconds, nanoseconds]
}
function hrtime(previousTimestamp?: HighResolutionTime): HighResolutionTime {
if (IS_BROWSER) {
return hrtimeBrowser(previousTimestamp)
} else {
return process.hrtime(previousTimestamp)
}
}
import { isObj } from 'exotic'
function toISOString(date?: Date) {
if (isObj(date) === true) {
return (date as Date).toISOString()
} else {
return 'xx-xx-xxx'
}
}
export class Timer {
public startWallTime?: Date
public endWallTime?: Date
public startHrTime?: HighResolutionTime
public duration?: HighResolutionTime
public static init() {
const timer = new Timer()
timer.start()
return timer
}
public start() {
this.startHrTime = hrtime()
this.startWallTime = new Date()
}
public end() {
this.duration = hrtime(this.startHrTime)
this.endWallTime = new Date()
}
public toString() {
if (this.duration === undefined) {
return 'unfinished'
} else {
return durationHrTimeToNanos(this.duration)
}
}
public toJSON() {
return {
durationInNanoSeconds: this.toString(),
startTime: toISOString(this.startWallTime),
endTime: toISOString(this.endWallTime),
}
}
}