traceperf
Version:
High-performance function execution tracking and monitoring for Node.js
106 lines • 2.58 kB
JavaScript
;
/**
* High-resolution timing utilities for performance tracking
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timer = void 0;
exports.getHighResTime = getHighResTime;
exports.getDuration = getDuration;
exports.formatDuration = formatDuration;
/**
* Get the current high-resolution time
*
* @returns The current high-resolution time
*/
function getHighResTime() {
return process.hrtime();
}
/**
* Calculate the duration between a start time and now
*
* @param startTime - The start time from getHighResTime()
* @returns The duration in milliseconds
*/
function getDuration(startTime) {
const [seconds, nanoseconds] = process.hrtime(startTime);
return seconds * 1000 + nanoseconds / 1000000;
}
/**
* Format a duration in milliseconds to a human-readable string
*
* @param duration - The duration in milliseconds
* @returns A formatted string (e.g., "1.23ms", "1.23s")
*/
function formatDuration(duration) {
if (duration < 1) {
return `${(duration * 1000).toFixed(2)}μs`;
}
else if (duration < 1000) {
return `${duration.toFixed(2)}ms`;
}
else {
return `${(duration / 1000).toFixed(2)}s`;
}
}
/**
* A simple timer class for measuring durations
*/
class Timer {
/**
* Create a new Timer instance
*
* @param label - A label for the timer
*/
constructor(label) {
this._endTime = null;
this._startTime = getHighResTime();
this._label = label;
}
/**
* Stop the timer
*
* @returns The duration in milliseconds
*/
stop() {
if (this._endTime === null) {
this._endTime = getHighResTime();
}
return this.getDuration();
}
/**
* Get the duration of the timer
*
* @returns The duration in milliseconds
*/
getDuration() {
if (this._endTime === null) {
return getDuration(this._startTime);
}
return getDuration(this._startTime);
}
/**
* Get the label of the timer
*
* @returns The timer label
*/
getLabel() {
return this._label;
}
/**
* Reset the timer
*/
reset() {
this._startTime = getHighResTime();
this._endTime = null;
}
/**
* Get a formatted string with the duration
*
* @returns A formatted string (e.g., "label: 1.23ms")
*/
toString() {
return `${this._label}: ${formatDuration(this.getDuration())}`;
}
}
exports.Timer = Timer;
//# sourceMappingURL=timing.js.map