@bemoje/profiler 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ var FunctionProfiler = require('../internal/FunctionProfiler/FunctionProfiler');
4
+ var ModuleMethodProfilerFactory = require('../internal/ProfilerFactory/ModuleMethodProfilerFactory');
5
+ var ProfilerWrapMethodsStrategy = require('../internal/ProfilerWrapMethodsStrategy/ProfilerWrapMethodsStrategy');
6
+ var PrototypeMethodProfilerFactory = require('../internal/ProfilerFactory/PrototypeMethodProfilerFactory');
7
+ var StandaloneFunctionIdentifier = require('../internal/FunctionIdentifier/StandaloneFunctionIdentifier');
8
+ var StaticMethodProfilerFactory = require('../internal/ProfilerFactory/StaticMethodProfilerFactory');
9
+ var table = require('@mono/table');
10
+ var util = require('util');
11
+ var predicate = require('es-toolkit/predicate');
12
+ var profilerWrap = require('../internal/FunctionProfiler/profilerWrap');
13
+ var fn = require('@mono/fn');
14
+
15
+ var __defProp = Object.defineProperty;
16
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
+ class Profiler {
18
+ static {
19
+ __name(this, "Profiler");
20
+ }
21
+ static enabled = true;
22
+ static get data() {
23
+ return FunctionProfiler.FunctionProfiler.instances.slice();
24
+ }
25
+ /**
26
+ *
27
+ */
28
+ static class(targetOrOptions, options) {
29
+ if (predicate.isFunction(targetOrOptions)) {
30
+ const target = targetOrOptions;
31
+ Profiler.classStatic(target, options?.ignoreStaticKeys);
32
+ Profiler.classPrototype(target, options?.ignorePrototypeKeys);
33
+ return target;
34
+ } else {
35
+ return (target) => {
36
+ return Profiler.class(target, targetOrOptions);
37
+ };
38
+ }
39
+ }
40
+ static classStatic(target, ignoreKeys) {
41
+ if (Profiler.enabled) {
42
+ fn.wrapMethods(target, new ProfilerWrapMethodsStrategy.ProfilerWrapMethodsStrategy(new StaticMethodProfilerFactory.StaticMethodProfilerFactory(target), [
43
+ ...ignoreKeys ?? [],
44
+ ...target.profiler?.ignoreStaticKeys ?? []
45
+ ]));
46
+ }
47
+ return target;
48
+ }
49
+ static classPrototype(target, ignoreKeys) {
50
+ if (Profiler.enabled) {
51
+ fn.wrapMethods(target.prototype, new ProfilerWrapMethodsStrategy.ProfilerWrapMethodsStrategy(new PrototypeMethodProfilerFactory.PrototypeMethodProfilerFactory(target.prototype), [
52
+ ...ignoreKeys ?? [],
53
+ ...target.profiler?.ignorePrototypeKeys ?? []
54
+ ]));
55
+ }
56
+ return target;
57
+ }
58
+ static module(target, moduleName, ignoreKeys) {
59
+ if (Profiler.enabled) {
60
+ fn.wrapMethods(target, new ProfilerWrapMethodsStrategy.ProfilerWrapMethodsStrategy(new ModuleMethodProfilerFactory.ModuleMethodProfilerFactory(moduleName, target), ignoreKeys));
61
+ }
62
+ return target;
63
+ }
64
+ static fn(nameOrFunc, maybeFunc) {
65
+ const func = predicate.isFunction(nameOrFunc) ? nameOrFunc : fn.setName(nameOrFunc, maybeFunc);
66
+ if (!func.name) {
67
+ throw new Error(`Function must have a name:
68
+ ${func.toString()}`);
69
+ }
70
+ if (Profiler.enabled) {
71
+ return profilerWrap.profilerWrap(func, new FunctionProfiler.FunctionProfiler(new StandaloneFunctionIdentifier.StandaloneFunctionIdentifier(func)));
72
+ }
73
+ return func;
74
+ }
75
+ static getResults(options) {
76
+ const results = Profiler.data.map((profiler) => {
77
+ return [
78
+ profiler.id.name,
79
+ profiler.getResult()
80
+ ];
81
+ });
82
+ const sortkey1 = options?.sortBy ?? "calls";
83
+ const sortValue1 = /* @__PURE__ */ __name((entry) => {
84
+ return entry[1][sortkey1] ?? -1;
85
+ }, "sortValue1");
86
+ const sortKey2 = sortkey1 === "calls" ? "totalTimeUs" : "calls";
87
+ const sortValue2 = /* @__PURE__ */ __name((entry) => {
88
+ return entry[1][sortKey2] ?? -1;
89
+ }, "sortValue2");
90
+ return results.sort((a, b) => {
91
+ const comparision = sortValue1(a) - sortValue1(b);
92
+ if (comparision !== 0) {
93
+ return comparision;
94
+ }
95
+ return sortValue2(a) - sortValue2(b);
96
+ });
97
+ }
98
+ static printResults(options) {
99
+ let entries = this.getResults(options);
100
+ if (options?.update) {
101
+ entries = options.update(entries);
102
+ }
103
+ const headers = [
104
+ "Execution time (microseconds)",
105
+ "calls",
106
+ "total",
107
+ "avg",
108
+ "min",
109
+ "max"
110
+ ];
111
+ const rows = entries.map(([method, stats]) => {
112
+ return [
113
+ method,
114
+ stats.calls,
115
+ stats.totalTimeUs,
116
+ stats.avgTimeUs,
117
+ stats.minTimeUs,
118
+ stats.maxTimeUs
119
+ ];
120
+ });
121
+ const table$1 = [
122
+ headers,
123
+ ...rows
124
+ ];
125
+ const formatter = new table.TableFormatter(table$1, {
126
+ color: !options?.noColor,
127
+ grayOutRow: /* @__PURE__ */ __name((row) => {
128
+ return row[1] === 0;
129
+ }, "grayOutRow")
130
+ });
131
+ console.log();
132
+ formatter.formattedLines.forEach((line) => {
133
+ return console.log(line);
134
+ });
135
+ console.log();
136
+ }
137
+ static [util.inspect.custom](depth, options = {}) {
138
+ options.compact = true;
139
+ return Object.fromEntries(this.getResults());
140
+ }
141
+ static toJSON() {
142
+ return this.getResults();
143
+ }
144
+ }
145
+
146
+ exports.Profiler = Profiler;
@@ -1,4 +1,4 @@
1
- import { inspect, InspectOptions } from 'node:util';
1
+ import { inspect, InspectOptions } from 'util';
2
2
 
3
3
  type Any = any;
4
4
 
@@ -0,0 +1,161 @@
1
+ import { inspect, InspectOptions } from 'util';
2
+
3
+ type Any = any;
4
+
5
+ type TFunction<R = Any, A extends Any[] = Any[]> = (...args: A) => R;
6
+
7
+ type FunctionPrototype = typeof Function.prototype;
8
+
9
+ type TargetType = 'static' | 'prototype' | 'module' | 'standalone';
10
+ type FunctionType = 'get' | 'set' | 'method' | 'function';
11
+
12
+ /**
13
+ * Abstract base class for identifying and naming functions in profiling contexts.
14
+ */
15
+ declare abstract class AbstractFunctionIdentifier<T extends FunctionPrototype | object> {
16
+ readonly target: T;
17
+ abstract readonly targetType: TargetType;
18
+ abstract readonly type: FunctionType;
19
+ abstract readonly name: string;
20
+ constructor(target: T);
21
+ toJSON(): string;
22
+ [inspect.custom](): string;
23
+ }
24
+
25
+ /**
26
+ * @see functionSpy
27
+ */
28
+ interface IFunctionSpyStrategy<T, Data> {
29
+ /**
30
+ * Action to perform before the function is invoked.
31
+ * @param thisContext The context in which the function is invoked.
32
+ * @param args The arguments passed to the function. Modify this array to change the arguments passed to the function.
33
+ * @returns Data to be passed to @see onReturn.
34
+ */
35
+ onInvoke<Args extends Any[]>(thisContext: T, args: Args): Data;
36
+ /**
37
+ * Action to perform before the function returns.
38
+ * @param data The data returned by @see onInvoke.
39
+ * @param retval The return value of the function.
40
+ * @returns The value to be returned by the wrapped function.
41
+ */
42
+ onReturn<Ret>(data: Data, retval: Ret): Ret;
43
+ }
44
+
45
+ /**
46
+ * Profiler for functions, measuring execution time and call counts.
47
+ */
48
+ declare class FunctionProfiler<T extends object> implements IFunctionSpyStrategy<T, bigint> {
49
+ readonly id: AbstractFunctionIdentifier<T>;
50
+ static instances: FunctionProfiler<object>[];
51
+ calls: number;
52
+ totalTimeNs?: number;
53
+ minTimeNs?: number;
54
+ maxTimeNs?: number;
55
+ constructor(id: AbstractFunctionIdentifier<T>);
56
+ /**
57
+ * Average execution time in nanoseconds
58
+ */
59
+ get avgTimeNs(): number | undefined;
60
+ /**
61
+ * Get the result of the profiling
62
+ */
63
+ getResult(): FunctionProfilerResult;
64
+ /**
65
+ * @see IFunctionSpyStrategy.onInvoke
66
+ */
67
+ onInvoke(): bigint;
68
+ /**
69
+ * @see IFunctionSpyStrategy.onReturn
70
+ */
71
+ onReturn<Ret>(t0: bigint, retval: Ret): Ret;
72
+ /**
73
+ * Add a new time measurement
74
+ */
75
+ protected add(t0: bigint, t1: bigint): void;
76
+ /**
77
+ * Nanoseconds to microseconds
78
+ */
79
+ protected nsToUs(ns: number): number;
80
+ [inspect.custom](): FunctionProfilerResult;
81
+ toJSON(): FunctionProfilerResult;
82
+ }
83
+ type FunctionProfilerResult = {
84
+ /**
85
+ * Number of method calls
86
+ */
87
+ calls: number;
88
+ /**
89
+ * Total execution time in microseconds
90
+ */
91
+ totalTimeUs?: number;
92
+ /**
93
+ * Total execution time in microseconds
94
+ */
95
+ avgTimeUs?: number;
96
+ /**
97
+ * Fastest execution time in microseconds
98
+ */
99
+ minTimeUs?: number;
100
+ /**
101
+ * Slowest execution time in microseconds
102
+ */
103
+ maxTimeUs?: number;
104
+ };
105
+
106
+ /**
107
+ * A utility class for profiling functions, classes, and modules to measure execution time and other performance metrics.
108
+ *
109
+ * @remarks
110
+ * The Profiler provides various static methods to wrap functions, classes, and modules with profiling functionality.
111
+ * This allows for detailed performance monitoring, including metrics like total execution time, average execution time,
112
+ * minimum and maximum execution times, and call counts.
113
+ *
114
+ * Profiling can be enabled or disabled globally using the `enabled` static property.
115
+ */
116
+ declare class Profiler {
117
+ static enabled: boolean;
118
+ static get data(): FunctionProfiler<object>[];
119
+ /**
120
+ * Class profiling
121
+ */
122
+ static class<T extends FunctionPrototype & {
123
+ profiler?: ProfilerClassOptions;
124
+ }>(target: T, options?: ProfilerClassOptions): T;
125
+ /**
126
+ * Class profiling decorator
127
+ */
128
+ static class<T extends FunctionPrototype & {
129
+ profiler?: ProfilerClassOptions;
130
+ }>(options: ProfilerClassOptions): (target: T) => T;
131
+ static classStatic<T extends FunctionPrototype & {
132
+ profiler?: ProfilerClassOptions;
133
+ }>(target: T, ignoreKeys?: Iterable<string | symbol>): T;
134
+ static classPrototype<T extends FunctionPrototype & {
135
+ profiler?: ProfilerClassOptions;
136
+ }>(target: T, ignoreKeys?: Iterable<string | symbol>): T;
137
+ static module<T extends object>(target: T, moduleName: string, ignoreKeys?: Iterable<string | symbol>): T;
138
+ static fn<T extends TFunction>(func: T): T;
139
+ static fn<T extends TFunction>(name: string, func: T): T;
140
+ static getResults(options?: GetProfilerResultsOptions): ProfilerResultReadableEntry[];
141
+ static printResults(options?: PrintProfilerResultsOptions): void;
142
+ static [inspect.custom](depth?: number, options?: InspectOptions): {
143
+ [k: string]: FunctionProfilerResult;
144
+ };
145
+ static toJSON(): ProfilerResultReadableEntry[];
146
+ }
147
+ type ProfilerClassOptions = {
148
+ ignoreStaticKeys?: Iterable<string | symbol>;
149
+ ignorePrototypeKeys?: Iterable<string | symbol>;
150
+ };
151
+ type GetProfilerResultsOptions = {
152
+ sortBy?: keyof FunctionProfilerResult;
153
+ };
154
+ type PrintProfilerResultsOptions = {
155
+ sortBy?: keyof FunctionProfilerResult;
156
+ update?: (entries: ProfilerResultReadableEntry[]) => ProfilerResultReadableEntry[];
157
+ noColor?: boolean;
158
+ };
159
+ type ProfilerResultReadableEntry = [string, FunctionProfilerResult];
160
+
161
+ export { Profiler };
@@ -0,0 +1,144 @@
1
+ import { FunctionProfiler } from '../internal/FunctionProfiler/FunctionProfiler';
2
+ import { ModuleMethodProfilerFactory } from '../internal/ProfilerFactory/ModuleMethodProfilerFactory';
3
+ import { ProfilerWrapMethodsStrategy } from '../internal/ProfilerWrapMethodsStrategy/ProfilerWrapMethodsStrategy';
4
+ import { PrototypeMethodProfilerFactory } from '../internal/ProfilerFactory/PrototypeMethodProfilerFactory';
5
+ import { StandaloneFunctionIdentifier } from '../internal/FunctionIdentifier/StandaloneFunctionIdentifier';
6
+ import { StaticMethodProfilerFactory } from '../internal/ProfilerFactory/StaticMethodProfilerFactory';
7
+ import { TableFormatter } from '@mono/table';
8
+ import { inspect } from 'util';
9
+ import { isFunction } from 'es-toolkit/predicate';
10
+ import { profilerWrap } from '../internal/FunctionProfiler/profilerWrap';
11
+ import { wrapMethods, setName } from '@mono/fn';
12
+
13
+ var __defProp = Object.defineProperty;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
+ class Profiler {
16
+ static {
17
+ __name(this, "Profiler");
18
+ }
19
+ static enabled = true;
20
+ static get data() {
21
+ return FunctionProfiler.instances.slice();
22
+ }
23
+ /**
24
+ *
25
+ */
26
+ static class(targetOrOptions, options) {
27
+ if (isFunction(targetOrOptions)) {
28
+ const target = targetOrOptions;
29
+ Profiler.classStatic(target, options?.ignoreStaticKeys);
30
+ Profiler.classPrototype(target, options?.ignorePrototypeKeys);
31
+ return target;
32
+ } else {
33
+ return (target) => {
34
+ return Profiler.class(target, targetOrOptions);
35
+ };
36
+ }
37
+ }
38
+ static classStatic(target, ignoreKeys) {
39
+ if (Profiler.enabled) {
40
+ wrapMethods(target, new ProfilerWrapMethodsStrategy(new StaticMethodProfilerFactory(target), [
41
+ ...ignoreKeys ?? [],
42
+ ...target.profiler?.ignoreStaticKeys ?? []
43
+ ]));
44
+ }
45
+ return target;
46
+ }
47
+ static classPrototype(target, ignoreKeys) {
48
+ if (Profiler.enabled) {
49
+ wrapMethods(target.prototype, new ProfilerWrapMethodsStrategy(new PrototypeMethodProfilerFactory(target.prototype), [
50
+ ...ignoreKeys ?? [],
51
+ ...target.profiler?.ignorePrototypeKeys ?? []
52
+ ]));
53
+ }
54
+ return target;
55
+ }
56
+ static module(target, moduleName, ignoreKeys) {
57
+ if (Profiler.enabled) {
58
+ wrapMethods(target, new ProfilerWrapMethodsStrategy(new ModuleMethodProfilerFactory(moduleName, target), ignoreKeys));
59
+ }
60
+ return target;
61
+ }
62
+ static fn(nameOrFunc, maybeFunc) {
63
+ const func = isFunction(nameOrFunc) ? nameOrFunc : setName(nameOrFunc, maybeFunc);
64
+ if (!func.name) {
65
+ throw new Error(`Function must have a name:
66
+ ${func.toString()}`);
67
+ }
68
+ if (Profiler.enabled) {
69
+ return profilerWrap(func, new FunctionProfiler(new StandaloneFunctionIdentifier(func)));
70
+ }
71
+ return func;
72
+ }
73
+ static getResults(options) {
74
+ const results = Profiler.data.map((profiler) => {
75
+ return [
76
+ profiler.id.name,
77
+ profiler.getResult()
78
+ ];
79
+ });
80
+ const sortkey1 = options?.sortBy ?? "calls";
81
+ const sortValue1 = /* @__PURE__ */ __name((entry) => {
82
+ return entry[1][sortkey1] ?? -1;
83
+ }, "sortValue1");
84
+ const sortKey2 = sortkey1 === "calls" ? "totalTimeUs" : "calls";
85
+ const sortValue2 = /* @__PURE__ */ __name((entry) => {
86
+ return entry[1][sortKey2] ?? -1;
87
+ }, "sortValue2");
88
+ return results.sort((a, b) => {
89
+ const comparision = sortValue1(a) - sortValue1(b);
90
+ if (comparision !== 0) {
91
+ return comparision;
92
+ }
93
+ return sortValue2(a) - sortValue2(b);
94
+ });
95
+ }
96
+ static printResults(options) {
97
+ let entries = this.getResults(options);
98
+ if (options?.update) {
99
+ entries = options.update(entries);
100
+ }
101
+ const headers = [
102
+ "Execution time (microseconds)",
103
+ "calls",
104
+ "total",
105
+ "avg",
106
+ "min",
107
+ "max"
108
+ ];
109
+ const rows = entries.map(([method, stats]) => {
110
+ return [
111
+ method,
112
+ stats.calls,
113
+ stats.totalTimeUs,
114
+ stats.avgTimeUs,
115
+ stats.minTimeUs,
116
+ stats.maxTimeUs
117
+ ];
118
+ });
119
+ const table = [
120
+ headers,
121
+ ...rows
122
+ ];
123
+ const formatter = new TableFormatter(table, {
124
+ color: !options?.noColor,
125
+ grayOutRow: /* @__PURE__ */ __name((row) => {
126
+ return row[1] === 0;
127
+ }, "grayOutRow")
128
+ });
129
+ console.log();
130
+ formatter.formattedLines.forEach((line) => {
131
+ return console.log(line);
132
+ });
133
+ console.log();
134
+ }
135
+ static [inspect.custom](depth, options = {}) {
136
+ options.compact = true;
137
+ return Object.fromEntries(this.getResults());
138
+ }
139
+ static toJSON() {
140
+ return this.getResults();
141
+ }
142
+ }
143
+
144
+ export { Profiler };
package/lib/index.cjs ADDED
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ var Profiler = require('./Profiler/Profiler');
4
+
5
+
6
+
7
+ Object.keys(Profiler).forEach(function (k) {
8
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
+ enumerable: true,
10
+ get: function () { return Profiler[k]; }
11
+ });
12
+ });
@@ -0,0 +1,2 @@
1
+ export { Profiler } from './Profiler/Profiler.cjs';
2
+ import 'util';
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { Profiler } from './Profiler/Profiler.js';
2
+ import 'util';
package/lib/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './Profiler/Profiler';
package/package.json CHANGED
@@ -1,38 +1,68 @@
1
1
  {
2
2
  "name": "@bemoje/profiler",
3
- "version": "2.0.1",
4
- "description": "profiler",
5
- "type": "module",
6
- "sideEffects": false,
3
+ "version": "2.2.0",
4
+ "description": "Performance profiling utilities for measuring execution time of functions, class methods, and modules.",
7
5
  "keywords": [
8
- "profiler"
6
+ "profiler",
7
+ "performance",
8
+ "profiling",
9
+ "execution-time",
10
+ "benchmarking",
11
+ "utilities",
12
+ "typescript"
9
13
  ],
10
- "exports": {
11
- ".": {
12
- "types": "./index.d.ts",
13
- "import": "./index.mjs",
14
- "default": "./index.mjs"
15
- }
16
- },
17
14
  "dependencies": {
18
- "ansi-colors": "^4.1.3",
19
- "enhanced-ms": "^4.1.0",
20
- "es-toolkit": "^1.44.0",
21
- "memoizee": "^0.4.17",
22
- "@types/memoizee": "^0.4.12"
15
+ "es-toolkit": "^1.45.1"
23
16
  },
17
+ "type": "module",
18
+ "sideEffects": false,
24
19
  "publishConfig": {
25
20
  "access": "public"
26
21
  },
27
- "license": "MIT",
28
- "author": {
29
- "name": "Benjamin Møller Jensen",
30
- "email": "bemoje@bemoje.net",
31
- "url": "https://github.com/bemoje/"
22
+ "main": "./lib/index.cjs",
23
+ "module": "./lib/index.js",
24
+ "types": "./lib/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./lib/index.d.ts",
29
+ "default": "./lib/index.js"
30
+ },
31
+ "require": {
32
+ "types": "./lib/index.d.cts",
33
+ "default": "./lib/index.cjs"
34
+ }
35
+ },
36
+ "./Profiler/Profiler": {
37
+ "import": {
38
+ "types": "./lib/Profiler/Profiler.d.ts",
39
+ "default": "./lib/Profiler/Profiler.js"
40
+ },
41
+ "require": {
42
+ "types": "./lib/Profiler/Profiler.d.cts",
43
+ "default": "./lib/Profiler/Profiler.cjs"
44
+ }
45
+ }
32
46
  },
47
+ "files": [
48
+ "./lib/index.js",
49
+ "./lib/index.d.ts",
50
+ "./lib/index.cjs",
51
+ "./lib/index.d.cts",
52
+ "./lib/Profiler/Profiler.js",
53
+ "./lib/Profiler/Profiler.d.ts",
54
+ "./lib/Profiler/Profiler.cjs",
55
+ "./lib/Profiler/Profiler.d.cts"
56
+ ],
33
57
  "repository": {
34
58
  "type": "git",
35
59
  "url": "git+https://github.com/bemoje/mono.git",
36
60
  "directory": "libs/profiler"
37
- }
61
+ },
62
+ "author": {
63
+ "name": "Benjamin Møller Jensen",
64
+ "email": "bemoje@bemoje.net",
65
+ "url": "https://github.com/bemoje/"
66
+ },
67
+ "license": "MIT"
38
68
  }