57 lines
1.4 KiB
JavaScript
57 lines
1.4 KiB
JavaScript
// Ported from nanotiming 7.3.1 (MIT) — https://github.com/choojs/nanotiming
|
|||
|
|
// Unified browser/Node implementation on the global `performance` object.
|
||
|
|
|
||
|
|
import { equal } from './assert.js'
|
||
|
|
|
||
|
|
const perf = typeof performance !== 'undefined' && typeof performance.mark === 'function'
|
||
|
|
? performance
|
||
|
|
: null
|
||
|
|
|
||
|
|
function checkDisabled () {
|
||
|
|
if (!perf) return true
|
||
|
|
if (typeof process !== 'undefined' && process.env && process.env.DISABLE_NANOTIMING) return true
|
||
|
|
if (typeof window !== 'undefined') {
|
||
|
|
try {
|
||
|
|
return window.localStorage.DISABLE_NANOTIMING === 'true'
|
||
|
|
} catch (e) {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
nanotiming.disabled = checkDisabled()
|
||
|
|
|
||
|
|
export default function nanotiming (name) {
|
||
|
|
equal(typeof name, 'string', 'nanotiming: name should be type string')
|
||
|
|
|
||
|
|
if (nanotiming.disabled) return noop
|
||
|
|
|
||
|
|
const uuid = (perf.now() * 10000).toFixed() % Number.MAX_SAFE_INTEGER
|
||
|
|
const startName = 'start-' + uuid + '-' + name
|
||
|
|
perf.mark(startName)
|
||
|
|
|
||
|
|
function end (cb) {
|
||
|
|
const endName = 'end-' + uuid + '-' + name
|
||
|
|
perf.mark(endName)
|
||
|
|
|
||
|
|
let err = null
|
||
|
|
try {
|
||
|
|
const measureName = name + ' [' + uuid + ']'
|
||
|
|
perf.measure(measureName, startName, endName)
|
||
|
|
perf.clearMarks(startName)
|
||
|
|
perf.clearMarks(endName)
|
||
|
|
} catch (e) { err = e }
|
||
|
|
if (cb) cb(err, name)
|
||
|
|
}
|
||
|
|
|
||
|
|
end.uuid = uuid
|
||
|
|
return end
|
||
|
|
}
|
||
|
|
|
||
|
|
function noop (cb) {
|
||
|
|
if (cb) {
|
||
|
|
cb(new Error('nanotiming: performance API unavailable or disabled'))
|
||
|
|
}
|
||
|
|
}
|