- node-tick-processor easy-to-install processor for the v8 profiler log
- node-gcstats exposes stats about V8 GC after it has been executed
- 0x single-command flamegraph profiling
- autocannon HTTP/1.1 benchmarking tool written in node, with support for HTTP pipelining and HTTPS
- k6.io open source load testing tool and SaaS for engineering teams
- why-did-you-render monkey patches React to notify you about avoidable re-renders (works with React Native as well)
3 авг. 2020 г.
Tools for performance analysis in Node.js
3 июн. 2020 г.
Profiling JavaScript code with Linux perf command
Profile V8 internals on Linux:
$ perf record d8 --perf-basic-prof test.js
$ perf report
More examples: http://www.brendangregg.com/perf.html#Examples
Easy installation of V8 engine: https://www.npmjs.com/package/jsvu
Customize output of Benchmark.js results
By default Benchmark.js recommends the following code to view results of a benchmark:
.on('cycle', function(event) {
console.log(String(event.target));
})
Example output:
<test 1> x 123,456 ops/sec ±5.67% (75 runs sampled)
<test 2> x 112,678 ops/sec ±4.56% (77 runs sampled)
The problem is that operations per second are not additive: if <test 2> has some added/removed code, we don't know the cost of that code in milliseconds (how many milliseconds it adds or removes from the total execution time).
To get that information, change the output code as follows:
.on('cycle', function(event) {
const stats = event.target.stats;
const sortedSample = stats.sample.sort((a, b) => b - a);
const median = sortedSample[sortedSample.length >> 1];
const fastest = sortedSample[sortedSample.length - 1];
console.log(
String(event.target),
'\n\tfastest:', fastest * 1000000, 'μs/op',
'\n\tmean:', stats.mean * 1000000, 'μs/op',
// '±' + stats.rme.toFixed(2) + '%',
'\n\tmedian:', median * 1000000, 'μs/op'
);
})
here stats.rme means "relative margin of error" and is the same "±5.67%" as in example output above, so there is no need to duplicate it
Same code in TypeScript:
.on('cycle', function(event: { target: { stats: Stats }; }) {
const stats: Stats = event.target.stats;
const sortedSample = stats.sample.sort((a, b) => b - a);
const median = sortedSample[sortedSample.length >> 1];
const fastest = sortedSample[sortedSample.length - 1];
console.log(
String(event.target),
'\n\tfastest:', fastest * 1000000, 'μs/op',
'\n\tmean:', stats.mean * 1000000, 'μs/op',
'\n\tmedian:', median * 1000000, 'μs/op'
);
})
Type description (borrowed from https://benchmarkjs.com/docs):
type Stats = {
/** The sample standard deviation. */
deviation: number,
/** The sample arithmetic mean (secs). */
mean: number,
/** The margin of error. */
moe: number,
/** The relative margin of error (expressed as a percentage of the mean). */
rme: number,
/** The array of sampled periods. */
sample: number[],
/** The standard error of the mean. */
sem: number,
/** The sample variance. */
variance: number
};
22 апр. 2020 г.
Location of browser extensions in macOS
10 апр. 2020 г.
Detect resized images on a page
This script detects resized images and background images, which consume your traffic and time. Images are visually marked as 1px dotted red, detailed information is written to the console of your DevTools.
https://gist.github.com/victor-homyakov/9c29b553270c5c71135a1746ab93325d
https://gist.github.com/victor-homyakov/9c29b553270c5c71135a1746ab93325d
7 апр. 2020 г.
19 мар. 2020 г.
Профилирование скорости server-side рендеринга (SSR) компонентов на React + TypeScript
Подготовка
Для запуска ts tsx файлов в Node.js устанавливаем пакет ts-node:npm i ts-node
Чтобы при запуске игнорировать импорт стилей в файле компонента (который может выглядеть примерно так: import './MyComponent.scss';), устанавливаем пакет ignore-styles:
npm i ignore-styles
Создание файла с бенчмарком
Создаём tsx файл, в котором импортируем наш компонент MyComponent, задаём props и вызываем renderToString():import * as React from 'react';
import { renderToString } from 'react-dom/server';
import { MyComponent } from './MyComponent';
const props = {/* ... */};
console.log(renderToString(<MyComponent {...props} />));
Запускаем его, чтобы убедиться, что всё работает без ошибок, компонент рендерится и в консоль выводится правильная разметка компонента:
NODE_ENV=production node -r ts-node/register -r ignore-styles MyComponent.perf-test.tsx
Если не хватит памяти, надо добавить параметр --max_old_space_size=4096
NODE_ENV=production node --max_old_space_size=4096 -r ts-node/register -r ignore-styles MyComponent.perf-test.tsx
Если памяти всё равно не хватит - надо поставить вместо 4096 число побольше. Запоминаем подобранные параметры.
Убедившись, что всё работает, в файле бенчмарка убираем вывод в консоль и дописываем вызов renderToString() в цикле:
import * as React from 'react';
import { renderToString } from 'react-dom/server';
import { MyComponent } from './MyComponent';
const props = {/* ... */};
for (let i = 0; i < 1000; i++) {
renderToString(<MyComponent {...props} />);
}
Запуск бенчмарка
Запускаем бенчмарк (в подобранную ранее командную строку добавляется параметр --prof):NODE_ENV=production node --prof -r ts-node/register -r ignore-styles MyComponent.perf-test.tsx
или
NODE_ENV=production node --prof --max_old_space_size=4096 -r ts-node/register -r ignore-styles MyComponent.perf-test.tsx
Первый запуск после изменения файла будет долгим и даст совсем неправильные результаты, т.к. под капотом компилируется TypeScript, и процесс компиляции тоже попадёт в собранный профиль, что нам не нужно. Поэтому после каждого редактирования запускаем бенчмарк по два раза, второй раз он выполнится быстрее.
После каждого запуска должны создаваться файлы isolate*.log.
Теперь вместо числа 1000 надо подобрать такое, чтобы второй запуск бенчмарка занимал достаточно продолжительное время (десятки секунд): меняем число, запускаем два раза, оцениваем продолжительность второго запуска.
После этого удаляем все накопившиеся файлы isolate*.log, запускаем бенчмарк ещё раз - мы должны получить ровно один файл isolate*.log.
Обработка и анализ собранного профиля
Полученный файл isolate*.log надо обработать, чтобы получить на выходе читабельный профиль выполнения:node --prof-process isolate-0x104000800-v8.log >isolate-0x104000800-v8.txt
Вместо isolate-0x104000800-v8 надо подставить своё имя файла. Также для обработки лога можно использовать отдельный пакет https://www.npmjs.com/package/tick-processor, часто он лучше обрабатывает лог и не теряет данные, в обличие от встроенного в саму ноду процессора логов:
tick-processor isolate-0x104000800-v8.log >isolate-0x104000800-v8.txt
В текстовом файле мы видим, какие именно методы v8 и нативного C++ кода вызывались и сколько времени заняли. Подробное описание содержимого и методов его анализа - тема, достойная отдельной большой статьи.
Подписаться на:
Сообщения (Atom)