Search
⌘K

Execution Timer

Utility for calculating the time taken to execute a piece of code.

Example Usage

import { createExecutionTimeMeter } from "./execution-timer";

// 1. init the timer
const executionTimer = createExecutionTimeMeter();

// 2. run your code ...

// 3. get elapsed time
const elapsedTime = executionTimer.getResult();
// ⏬
{
  inMs: 2000,
  humanReadable: '2s,
}

Dependencies

registryhttps://shadcn-registry-ts.vercel.app/r/util-date-time.json

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-execution-timer.json

Manual Install

execution-timer.ts
/**
 * Source: http://localhost:3000
 */

import { formatMillisecondsToHumanReadable } from "./date-time";

/**
 * Simple time execution tracker for meaasuring the time taken to execute a function.
 * 
 * @example
 * const executionTimer = createExecutionTimeMeter();
 * // ... run your code
 * const elapsedTimeInMs = executionTimer.getResult(); 
 * // output 
 * {
 *   inMs: 2000,
 *   humanReadable: TODO
 * }
 */
export const createExecutionTimeMeter = () => {
  const start = performance.now();

  const getResult = () => {
    const end = performance.now();
    const elapsedTimeInMs = end - start;
    const elapsedTimeHumanReadable = formatMillisecondsToHumanReadable(elapsedTimeInMs);
    return {
      inMs: elapsedTimeInMs,
      humanReadable: elapsedTimeHumanReadable,
    };
  };

  return {
    getResult
  };
};

export type ExecutionTimeMeter = ReturnType<typeof createExecutionTimeMeter>;

Test

execution-timer.test.ts
import { describe, it, expect } from 'vitest';
import { repeatAsyncFnInParallel } from '../utility-framework/vitest.utils';
import { sleep } from './sleep';

import { createExecutionTimeMeter } from './execution-timer';

describe('execution-timer', { timeout: 60_000 }, () => {

  it('do it', async () => {

    await repeatAsyncFnInParallel(1_000, async () => {
      const timer = createExecutionTimeMeter();
      await sleep(2000);
      const result = timer.getResult();

      expect(result).toBeTypeOf('object');
      expect(result.inMs).toBeTypeOf('number');
      expect(result.humanReadable).toBeTypeOf('string');
      expect(result.humanReadable).oneOf(['2s', "2.1s"]);
    });

  });

});

Command Palette

Search for a command to run...