Skip to content

Commit

Permalink
add time utils
Browse files Browse the repository at this point in the history
  • Loading branch information
mangs committed Feb 19, 2024
1 parent bb018e2 commit 493ec4a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 19 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"exports": {
"./build": "./utils/buildUtils.mts",
"./console": "./utils/consoleUtils.mts",
"./filesystem": "./utils/filesystemUtils.mts"
"./filesystem": "./utils/filesystemUtils.mts",
"./time": "./utils/timeUtils.mts"
},
"scripts": {
"audit:node-modules": "cd node_modules && du -sh -- * | sort -h",
Expand Down
22 changes: 4 additions & 18 deletions utils/consoleUtils.mts
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
// External Imports
import { cyan, dim, green, red, white, yellow } from 'yoctocolors';

// Local Variables
const timeUnits = ['ns', 'μs', 'ms', 's'] as const;
// Internal Imports
import { getElapsedTimeFormatted } from './timeUtils.mts';

// Local Functions
function getPerformanceLabel(startTime: number) {
const endTime = Bun.nanoseconds();
let elapsedTime = endTime - startTime;
let timeIndex = 0;
while (elapsedTime > 1) {
if (elapsedTime <= 1_000) {
break;
}
elapsedTime /= 1_000;
timeIndex += 1;
}
const elapsedTimeLocalized = elapsedTime.toLocaleString(undefined, {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
const units = timeUnits[timeIndex];
return dim(white(`[${elapsedTimeLocalized}${units}]`));
const formattedTime = getElapsedTimeFormatted(startTime);
return dim(white(`[${formattedTime}]`));
}

function printError(message: string) {
Expand Down
25 changes: 25 additions & 0 deletions utils/timeUtils.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Local Variables
const timeUnits = ['ns', 'μs', 'ms', 's'] as const;

// Local Functions
function getElapsedTimeFormatted(startTime: number) {
const endTime = Bun.nanoseconds();
let elapsedTime = endTime - startTime;
let timeIndex = 0;
while (elapsedTime > 1) {
if (elapsedTime <= 1_000) {
break;
}
elapsedTime /= 1_000;
timeIndex += 1;
}
const elapsedTimeLocalized = elapsedTime.toLocaleString(undefined, {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
const units = timeUnits[timeIndex];
return `${elapsedTimeLocalized}${units}`;
}

// Module Exports
export { getElapsedTimeFormatted };

0 comments on commit 493ec4a

Please sign in to comment.