perf_hooks#performance TypeScript Examples

The following examples show how to use perf_hooks#performance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: datadog-util.ts    From bodhi.js with Apache License 2.0 7 votes vote down vote up
buildTracerSpan = (): DataDogTracerSpan | undefined => {
  // Get datadog span from the context
  const span = process.env.EXTENSIVE_DD_INSTRUMENTATION == 'true' ? tracer.scope().active() : null;
  // Initialize datadog span tags
  const spanTags = span
    ? {
        body: {},
        enterTime: performance.now(),
        exitTime: -1,
        elapsedTime: -1,
        spanRef: span
      }
    : undefined;
  return spanTags;
}
Example #2
Source File: utils.ts    From icepkg with MIT License 7 votes vote down vote up
timeFrom = (start: number, subtract = 0): string => {
  const time: number | string = performance.now() - start - subtract;
  const timeString = (`${time.toFixed(2)} ms`).padEnd(5, ' ');
  if (time < 10) {
    return picocolors.green(timeString);
  } else if (time < 50) {
    return picocolors.yellow(timeString);
  } else {
    return picocolors.red(timeString);
  }
}
Example #3
Source File: common.ts    From jekyll-action-ts with MIT License 6 votes vote down vote up
export async function measure<T>({
	name,
	block,
}: {
	name: string;
	block: () => Promise<T>;
}): Promise<void> {
	return await core.group(name, async () => {
		const start = performance.now();
		try {
			await block();
		} catch (error) {
			core.setFailed(error.message);
		} finally {
			const end = performance.now();
			const duration = (end - start) / 1000.0;
			core.info(`Took ${duration.toFixed(2).padStart(6)} seconds`);
		}
	});
}
Example #4
Source File: index.ts    From external-protocol-flooding with MIT License 6 votes vote down vote up
app.post('/app_hashes', async (req, res) => {
  const { visitorId, appHash } = req.body

  if (!appHash || appHash.length === 0) {
    const err = 'appHash value is required' 
    console.warn(err)
    res.status(422).send({ ok: false, error: err})
    return
  }

  let count = 0
  let totalCount = 0

  try {
    const startedTimestamp = performance.now()
    let result =
      await dbPool.query('SELECT COUNT(1) as count FROM app_hashes WHERE app_hash = $1', [appHash])

    count = result.rows[0].count

    result = await dbPool.query('SELECT COUNT(id) as count FROM app_hashes')
    totalCount = result.rows[0].count

    await dbPool.query('INSERT INTO app_hashes (visitor_id, app_hash) VALUES ($1, $2)', [
      visitorId,
      appHash,
    ])
    const duration = Math.round(performance.now() - startedTimestamp)
    res.status(202).send({ ok: true, duration: `${duration}ms`, count, totalCount })
  } catch (e) {
    console.error(e)
    res.status(422).send({ ok: false, error: 'Failed to add appHash' })
  }
})
Example #5
Source File: fs.test.ts    From normalize-japanese-addresses with MIT License 6 votes vote down vote up
test('normalize should complete in the local environment', async () => {
  const started1 = performance.now()
  await normalize('京都府京田辺市同志社山手4丁目1-43')
  const finished1 = performance.now()
  console.log('nocache performance(ms): ', finished1 - started1)

  const started2 = performance.now()
  await normalize('京都府京田辺市同志社山手4丁目1-44')
  const finished2 = performance.now()
  console.log('with-cache performance(ms): ', finished2 - started2)

  expect(unfetch).not.toBeCalled()
})
Example #6
Source File: stripeLinter.ts    From vscode-stripe with MIT License 6 votes vote down vote up
lookForHardCodedAPIKeys = async (document: TextDocument): Promise<void> => {
    performance.mark('ignore-start');
    const isIgnored = await this.git.isIgnored(document.uri);
    performance.mark('ignore-end');
    performance.measure('ignore', 'ignore-start', 'ignore-end');

    if (isIgnored || document.fileName.endsWith('.env')) {
      diagnosticCollection.delete(document.uri);
      return;
    }

    const text = document.getText();
    const lines = text.split('\n');

    const message = (await this.git.isGitRepo(document.uri))
      ? diagnosticMessageGit
      : diagnosticMessageNoGit;

    const fileDiagnostics: Diagnostic[] = lines.flatMap(this.prepareLineDiagnostics(message));

    // tell VS Code to show warnings and errors in syntax
    diagnosticCollection.set(document.uri, fileDiagnostics);
  };
Example #7
Source File: utils.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
export function timer(fn: () => void): number {
  const start = performance.now()
  fn()
  const end = performance.now() - start
  return end
}
Example #8
Source File: buildAll.ts    From icepkg with MIT License 6 votes vote down vote up
buildAll = async (cfgArrs: TaskLoaderConfig[], ctx: PkgContext) => {
  for (let c = 0; c < cfgArrs.length; ++c) {
    const { type } = cfgArrs[c];

    let outputFiles: OutputFile[] = [];
    if (type === 'bundle') {
      outputFiles = await runBundle(cfgArrs[c]);
    }

    if (type === 'transform') {
      outputFiles = await runTransform(cfgArrs[c], ctx);
    }

    const reportSizeStart = performance.now();
    if (ctx.command === 'build') {
      reportSize(outputFiles.reduce((pre, chunk) => {
        return {
          ...pre,
          [chunk.filename]: chunk.code ? chunk.code : fs.readFileSync(chunk.dest),
        };
      }, ({} as any)));
    }

    const logger = createLogger('report-size');
    logger.debug(`ReportSize consume ${timeFrom(reportSizeStart)}`);
  }
}
Example #9
Source File: performanceTracker.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
protected stopTimer(tag = this.tag): number {
    if (!PerformanceTracker.enabled) return 0;
    const startTime = PerformanceTracker.performanceTimes[tag];
    if (!startTime) throw new Error('Timer not started');

    const totalTime = performance.now() - startTime;
    PerformanceTracker.performanceTimes[tag] = undefined;

    return totalTime;
  }
Example #10
Source File: util.test.ts    From js-sdk with MIT License 6 votes vote down vote up
describe("Utils", () => {
    it("should be able to determine if this is JSON structure or not.", done => {
        const json = `
        {
            "hi": "message",
            "im": "json"
        }
        `

        const brokenJson = `
        {
            'hi': 'message',
            'im': 'broken json, single quotes is not allowed.'
        }
        `

        const parsedJson = Utils.isJSON(json)
        const parsedBrokenJson = Utils.isJSON(brokenJson)

        expect(parsedJson).toBe(true)
        expect(parsedBrokenJson).toBe(false)

        done()
    })

    it("should be able to freeze asynchronously.", async () => {
        const time = performance.now()

        await Utils.waitFor(100)

        expect(performance.now() - time).toBeLessThanOrEqual(150)

        return
    })

    it("KoreanbotsAPIError", () => {
        const ERROR_MESSAGE = "test error"
        const ERROR_CODE = 400
        const ERROR_METHOD = "POST"
        const ERROR_PATH = "/"

        const error = new KoreanbotsAPIError(ERROR_MESSAGE, ERROR_CODE, ERROR_METHOD, ERROR_PATH)

        try {
            throw error
        } catch (e) {
            expect(e.message).toBe(ERROR_MESSAGE)
            expect(e.code).toBe(ERROR_CODE)
            expect(e.method).toBe(ERROR_METHOD)
            expect(e.path).toBe(ERROR_PATH)
        } finally {
            // eslint-disable-next-line no-unsafe-finally
            return 
        }
    })
})
Example #11
Source File: server.ts    From vite-ssr with MIT License 6 votes vote down vote up
export function printServerInfo(server: ViteDevServer) {
  const info = server.config.logger.info

  let ssrReadyMessage = '\n -- SSR mode'

  if (Object.prototype.hasOwnProperty.call(server, 'printUrls')) {
    info(
      chalk.cyan(`\n  vite v${require('vite/package.json').version}`) +
        chalk.green(` dev server running at:\n`),
      { clear: !server.config.logger.hasWarned }
    )

    // @ts-ignore
    server.printUrls()

    // @ts-ignore
    if (globalThis.__ssr_start_time) {
      ssrReadyMessage += chalk.cyan(
        ` ready in ${Math.round(
          // @ts-ignore
          performance.now() - globalThis.__ssr_start_time
        )}ms.`
      )
    }
  }

  info(ssrReadyMessage + '\n')
}
Example #12
Source File: router.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(list: TConstructor[], module: Module, moduleList: Module[], args: CmdArgs) {
    this.listConstructors = list;
    this.args = args;
    this.list = list.map((PluginToLoad) => {
      if (this.args.performance && Router.timeTaken[PluginToLoad.name] == null) {
        Router.timeTaken[PluginToLoad.name] = 0;
      }
      return new PluginToLoad(args, module, moduleList);
    });
    this.maxPass = Math.max(...this.list.map((plugin) => plugin.pass));

    this.module = module;
    this.moduleList = moduleList;
  }
Example #13
Source File: diagnosticHelper.ts    From coffeesense with MIT License 6 votes vote down vote up
// Retry to get diagnostics until length > 0 or timeout
export async function getDiagnosticsAndTimeout(docUri: vscode.Uri, timeout = 5000) {
  const startTime = performance.now();

  let result = vscode.languages.getDiagnostics(docUri);

  while (result.length <= 0 && startTime + timeout > performance.now()) {
    result = vscode.languages.getDiagnostics(docUri);
    await sleep(100);
  }

  return result;
}
Example #14
Source File: main.ts    From osmosfeed with MIT License 6 votes vote down vote up
async function run() {
  const startTime = performance.now();
  console.log(`[main] Starting build using cli version ${cliVersion}`);

  const systemFiles = await discoverSystemFiles();
  const config = await getConfig(systemFiles.configFile);
  const userFiles = await discoverUserFiles();

  const cache = await getCache({ cacheUrl: config.cacheUrl, localCacheFile: systemFiles.localCacheFile });

  const enrichedSources: EnrichedSource[] = (
    await Promise.all(config.sources.map((source) => enrich({ source, cache, config })))
  ).filter(isNotNull);

  const executableTemplate = compileTemplates({
    userTemplates: userFiles.userTemplateFiles,
    systemTemplates: systemFiles.systemTemplateFiles,
  });
  const userSnippets = getSnippets(userFiles.userSnippetFiles);

  const baseHtml = executableTemplate(getTemplateData({ enrichedSources, config }));
  const userCustomizedHtml = renderUserSnippets({ baseHtml, userSnippets, config });
  const atom = renderAtom({ enrichedSources, config });
  await writeFiles({ html: userCustomizedHtml, atom });

  const copyPlan = getCopyStaticPlan({
    userStaticFiles: userFiles.userStaticFiles,
    userTemplateFiles: userFiles.userTemplateFiles,
    systemStaticFiles: systemFiles.systemStaticFiles,
    systemTemplateStaticFiles: systemFiles.systemTemplateStaticFiles,
  });

  await copyStatic(copyPlan);

  await setCache({ sources: enrichedSources, cliVersion });

  const durationInSeconds = ((performance.now() - startTime) / 1000).toFixed(2);
  console.log(`[main] Finished build in ${durationInSeconds} seconds`);
}
Example #15
Source File: performanceTracker.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
protected stopTimer(tag = this.tag): number {
    if (!PerformanceTracker.enabled) return 0;
    const startTime = PerformanceTracker.performanceTimes[tag];
    if (!startTime) throw new Error('Timer not started');

    const totalTime = performance.now() - startTime;
    PerformanceTracker.performanceTimes[tag] = undefined;

    return totalTime;
  }
Example #16
Source File: ProcessingTimeUtil.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
public Measure(context: string = "", infoThld: number = 0, warningThld = 0) {
        if (!this.devMode){
            return;
        }

        if (infoThld === 0) {
            infoThld = this.defaultInfoThld;
        }
        if (warningThld === 0) {
            warningThld = this.defaultWarningThld;
        }

        let endingTime: number = performance.now();
        let runTime: number = Math.round(((endingTime) - this.startingTime) * 100 / 100);

        let msgText = `Process ${context !== "" ? "'" + context + "'" : ""} took ${runTime}ms to finish. Threshold is defined at: `;

        if (runTime >= warningThld) {
            console.warn(`${msgText}${warningThld}ms.`);
            return;
        }
        if (runTime >= infoThld) {
            console.info(`${msgText}${infoThld}ms.`);
            return;
        }
    }
Example #17
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
mark.end = function markEnd(name: string) {
  if (marks[name]) {
    const markB = name + '_B';
    performance.mark(markB);
    performance.measure(marks[name], name, markB);
    delete marks[name];
  } else {
    throw new Error(`Can't place end mark, mark "${name}" doesn't exists`);
  }
};
Example #18
Source File: Kernel.ts    From civet with MIT License 6 votes vote down vote up
function Benchmark(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  Initialze()
  const primitive = descriptor.value
  descriptor.value = function (...args: any) {
    performance.mark(`${propertyKey} begin`)
    const result = primitive(...args)
    performance.mark(`${propertyKey} end`)
    performance.measure(`${propertyKey} time:`, `${propertyKey} begin`, `${propertyKey} end`)
    return result
  }
  return descriptor
}
Example #19
Source File: perf.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
function bench(name: string, fn: () => void, durationSeconds = 5) {
    let startTs = performance.now();
    let endTs = startTs + durationSeconds * 1000;
    let samples = 0;
    while (performance.now() < endTs) {
        fn();
        samples++;
    }
    let durationMs = performance.now() - startTs;
    let opsPerSecond = 1000 / (durationMs / samples);
    console.log(`${name}: ${formatNumber(opsPerSecond)} ops/s`);
}
Example #20
Source File: impl.ts    From kassette with MIT License 6 votes vote down vote up
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////

export async function measure(callback: Function) {
  const { now } = performance;

  const start = now();
  const output = await callback();
  const end = now();

  return {
    start,
    end,
    duration: end - start,
    output,
  };
}
Example #21
Source File: bench-from-char-code.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
function bench(name: string, fn: () => void, durationSeconds = 5) {
    let startTs = performance.now();
    let endTs = startTs + durationSeconds * 1000;
    let samples = 0;
    while (performance.now() < endTs) {
        fn();
        samples++;
    }
    let durationMs = performance.now() - startTs;
    let opsPerSecond = 1000 / (durationMs / samples);
    let numFmt = (n: number) => new Intl.NumberFormat("en-US").format(n);
    console.log(`${name}: ${numFmt(opsPerSecond)} ops/s`);
}
Example #22
Source File: update-person-properties.benchmark.ts    From posthog-foss with MIT License 6 votes vote down vote up
async function runUpdateCycle(
    hub: Hub,
    teamId: number,
    startingProperties: Record<string, any>,
    propertyUpdates: Record<string, any>,
    propertyToOperationMap: Record<string, PropertyUpdateOperation>,
    isControl = false
): Promise<number> {
    const uuid = new UUIDT().toString()
    const distinctId = String(Math.random() + Math.random())
    const person = await hub.db.createPerson(DateTime.now(), startingProperties, teamId, null, false, uuid, [
        distinctId,
    ])

    const startTime = performance.now()
    if (isControl) {
        await hub.db.updatePerson(person, { properties: propertyUpdates })
    } else {
        await hub.db.updatePersonProperties(person, propertyUpdates, propertyToOperationMap, new Date().toISOString())
    }
    const endTime = performance.now()
    return endTime - startTime
}
Example #23
Source File: bench-base64-encode.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
function bench(name: string, fn: () => void, durationSeconds = 5) {
    let startTs = performance.now();
    let endTs = startTs + durationSeconds * 1000;
    let samples = 0;
    while (performance.now() < endTs) {
        fn();
        samples++;
    }
    let durationMs = performance.now() - startTs;
    let opsPerSecond = 1000 / (durationMs / samples);
    let numFmt = (n: number) => new Intl.NumberFormat("en-US").format(n);
    console.log(`${name}: ${numFmt(opsPerSecond)} ops/s`);
}
Example #24
Source File: process-event.ts    From posthog-foss with MIT License 6 votes vote down vote up
// 600 sec timeout.

export async function delayUntilEventIngested(
    fetchEvents: () => Promise<any[] | any>,
    minCount = 1,
    delayMs = 500,
    maxDelayCount = 30,
    debug = false
): Promise<void> {
    const timer = performance.now()
    for (let i = 0; i < maxDelayCount; i++) {
        const events = await fetchEvents()
        if (debug) {
            console.log(
                `Waiting. ${Math.round((performance.now() - timer) / 100) / 10}s since the start. ${
                    typeof events === 'number' ? events : events.length
                } events.`
            )
        }
        if ((typeof events === 'number' ? events : events.length) >= minCount) {
            return
        }
        await delay(delayMs)
    }
}
Example #25
Source File: bench-base64-decode.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
function bench(name: string, fn: () => void, durationSeconds = 5) {
    let startTs = performance.now();
    let endTs = startTs + durationSeconds * 1000;
    let samples = 0;
    while (performance.now() < endTs) {
        fn();
        samples++;
    }
    let durationMs = performance.now() - startTs;
    let opsPerSecond = 1000 / (durationMs / samples);
    let numFmt = (n: number) => new Intl.NumberFormat("en-US").format(n);
    console.log(`${name}: ${numFmt(opsPerSecond)} ops/s`);
}
Example #26
Source File: performanceTracker.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
protected startTimer(tag = this.tag): void {
    if (!PerformanceTracker.enabled) return;
    PerformanceTracker.performanceTimes[tag] = performance.now();
  }
Example #27
Source File: index.ts    From abck with MIT License 5 votes vote down vote up
/**
   * Needs to be executed inside browser/electron app (returns weird results in node)
   * @returns getmr
   */
  public static getmr(): string {
    const functions = [
      Math.abs,
      Math.acos,
      Math.asin,
      Math.atanh,
      Math.cbrt,
      Math.exp,
      Math.random,
      Math.round,
      Math.sqrt,
      // eslint-disable-next-line no-restricted-globals
      isFinite,
      // eslint-disable-next-line no-restricted-globals
      isNaN,
      parseFloat,
      parseInt,
      JSON.parse,
    ];
    let t = '';
    functions.forEach((func) => {
      const o = [];
      let m = 0;
      const r = performance.now();
      let i = 0;
      let c = 0;
      if (undefined !== func) {
        for (i = 0; i < 1000 && m < 0.6; i++) {
          const b = performance.now();
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          for (let d = 0; d < 4e3; d++) func(3.14);
          const k = performance.now();
          o.push(Math.round(1e3 * (k - b)));
          m = k - r;
        }
        const s = o.sort();
        c = s[Math.floor(s.length / 2)] / 5;
      }
      t = `${t}${c},`;
    });
    return t;
  }
Example #28
Source File: Stopwatch.ts    From yumeko with GNU Affero General Public License v3.0 5 votes vote down vote up
public begin = performance.now();
Example #29
Source File: router.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
runPass = (pass: number): void => {
    if (this.module.failedToDecompile) return;
    try {
      const passPlugins = this.list.map((plugin, index) => ({ plugin, index })).filter(({ plugin }) => plugin.pass === pass);

      if (this.args.debug === this.module.moduleId) {
        this.runDebugPass(passPlugins.map(({ plugin }) => plugin));
      }

      let startTime = performance.now();
      const visitorFunctions: { [index: string]: ((path: NodePath<unknown>) => void)[] } = {};

      passPlugins.forEach(({ plugin, index }) => {
        if (plugin.evaluate) {
          this.performanceTrack(this.listConstructors[index].name, () => plugin.evaluate && plugin.evaluate(this.module.rootPath, this.runPlugin));
        } else if (plugin.getVisitor) {
          // disable some eslint rules from object mapping
          /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return */
          const visitor: any = plugin.getVisitor(this.runPlugin);
          Object.keys(visitor).forEach((key) => {
            if (!visitorFunctions[key]) {
              visitorFunctions[key] = [];
            }
            if (this.args.performance) {
              visitorFunctions[key].push((path: NodePath<unknown>) => {
                Router.traverseTimeTaken += performance.now() - startTime;
                this.performanceTrack(this.listConstructors[index].name, () => visitor[key](path));
                startTime = performance.now();
              });
            } else {
              visitorFunctions[key].push(visitor[key]);
            }
          });
        } else {
          throw new Error('Plugin does not have getVisitor nor evaluate');
        }
      });

      const visitor: any = {};
      Object.keys(visitorFunctions).forEach((key) => {
        visitor[key] = this.processVisit(visitorFunctions[key]);
      });
      /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return */
      if (Object.keys(visitor).length > 0) {
        startTime = performance.now();
        this.module.rootPath.traverse(visitor);
        Router.traverseTimeTaken += performance.now() - startTime;
      }

      passPlugins.forEach(({ plugin, index }) => {
        this.performanceTrack(this.listConstructors[index].name, () => plugin.afterPass && plugin.afterPass(this.runPlugin));
      });
    } catch (e) {
      console.error(`An error occured parsing module ${this.module.moduleId}, it will be outputted as is!`);
      console.error(e);
      this.module.failedToDecompile = true;
    }
  };