@eagleoutice/flowr
Version:
Static Dataflow Analyzer and Program Slicer for the R Programming Language
79 lines • 2.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Measurements = void 0;
const assert_1 = require("../util/assert");
/** unguarded start-stop wrapper */
class Stopwatch {
timeStart;
timeEnd;
stopped = false;
start() {
this.timeStart = process.hrtime.bigint();
}
stop() {
this.timeEnd = process.hrtime.bigint();
// check after to not affect measurements
(0, assert_1.guard)(!this.stopped, 'cannot stop a stopwatch twice');
this.stopped = true;
}
get() {
(0, assert_1.guard)(this.timeStart !== undefined && this.timeEnd !== undefined, 'cannot get elapsed time as the stopwatch has not been started/stopped');
return this.timeEnd - this.timeStart;
}
}
/**
* Allows to measure keys of type `T` with a `Stopwatch`.
*
* Measure with {@link start}, {@link measure} or {@link measureAsync}, retrieve the final measurements with {@link get}.
*/
class Measurements {
measurements = new Map();
/**
* Start a timer for the given key, and guards that this is the first time this key is started.
* Call {@link IStoppableStopwatch#stop} on the returned stopwatch to stop the timer.
*/
start(key) {
// we guard *before* starting so there is no additional time penalty
(0, assert_1.guard)(!this.measurements.has(key), `already started stop watch for ${JSON.stringify(key)}`);
const stopwatch = new Stopwatch();
this.measurements.set(key, stopwatch);
stopwatch.start();
return stopwatch;
}
/**
* Automatically call {@link Measurements#start | start} and the corresponding stop to measure the execution time of the given function.
* @see {@link measureAsync}
*/
measure(key, fn) {
const stopwatch = this.start(key);
const result = fn();
stopwatch.stop();
return result;
}
/**
* Similar to {@link measure}, but await the promise as part of the measurement
*
* @param key - The key to write the resulting measurement to
* @param fn - The function to measure
*
* @see measure
*/
async measureAsync(key, fn) {
const stopwatch = this.start(key);
const result = await fn();
stopwatch.stop();
return result;
}
/**
* Retrieve all measure-results, requires that all stop-watches that have been started have also been stopped.
*/
get() {
const result = new Map();
for (const [key, stopwatch] of this.measurements) {
result.set(key, stopwatch.get());
}
return result;
}
}
exports.Measurements = Measurements;
//# sourceMappingURL=stopwatch.js.map