Release 1.0.36
[e-mobility-charging-stations-simulator.git] / src / utils / PerformanceStatistics.ts
... / ...
CommitLineData
1import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from './CircularArray';
2import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
3import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
4import Statistics, { StatisticsData } from '../types/Statistics';
5
6import Configuration from './Configuration';
7import { MessageType } from '../types/ocpp/MessageType';
8import Utils from './Utils';
9import logger from './Logger';
10
11export default class PerformanceStatistics {
12 private objId: string;
13 private performanceObserver: PerformanceObserver;
14 private statistics: Statistics;
15 private displayInterval: NodeJS.Timeout;
16
17 public constructor(objId: string) {
18 this.objId = objId;
19 this.initializePerformanceObserver();
20 this.statistics = { id: this.objId ?? 'Object id not specified', statisticsData: {} };
21 }
22
23 public static beginMeasure(id: string): string {
24 const beginId = 'begin' + id.charAt(0).toUpperCase() + id.slice(1);
25 performance.mark(beginId);
26 return beginId;
27 }
28
29 public static endMeasure(name: string, beginId: string): void {
30 performance.measure(name, beginId);
31 performance.clearMarks(beginId);
32 }
33
34 public addRequestStatistic(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void {
35 switch (messageType) {
36 case MessageType.CALL_MESSAGE:
37 if (this.statistics.statisticsData[command] && this.statistics.statisticsData[command].countRequest) {
38 this.statistics.statisticsData[command].countRequest++;
39 } else {
40 this.statistics.statisticsData[command] = {} as StatisticsData;
41 this.statistics.statisticsData[command].countRequest = 1;
42 }
43 break;
44 case MessageType.CALL_RESULT_MESSAGE:
45 if (this.statistics.statisticsData[command]) {
46 if (this.statistics.statisticsData[command].countResponse) {
47 this.statistics.statisticsData[command].countResponse++;
48 } else {
49 this.statistics.statisticsData[command].countResponse = 1;
50 }
51 } else {
52 this.statistics.statisticsData[command] = {} as StatisticsData;
53 this.statistics.statisticsData[command].countResponse = 1;
54 }
55 break;
56 case MessageType.CALL_ERROR_MESSAGE:
57 if (this.statistics.statisticsData[command]) {
58 if (this.statistics.statisticsData[command].countError) {
59 this.statistics.statisticsData[command].countError++;
60 } else {
61 this.statistics.statisticsData[command].countError = 1;
62 }
63 } else {
64 this.statistics.statisticsData[command] = {} as StatisticsData;
65 this.statistics.statisticsData[command].countError = 1;
66 }
67 break;
68 default:
69 logger.error(`${this.logPrefix()} wrong message type ${messageType}`);
70 break;
71 }
72 }
73
74 public start(): void {
75 this.startDisplayInterval();
76 }
77
78 public stop(): void {
79 if (this.displayInterval) {
80 clearInterval(this.displayInterval);
81 }
82 performance.clearMarks();
83 this.performanceObserver?.disconnect();
84 }
85
86 public restart(): void {
87 this.stop();
88 this.start();
89 }
90
91 private initializePerformanceObserver(): void {
92 this.performanceObserver = new PerformanceObserver((list) => {
93 this.addPerformanceEntryToStatistics(list.getEntries()[0]);
94 logger.debug(`${this.logPrefix()} '${list.getEntries()[0].name}' performance entry: %j`, list.getEntries()[0]);
95 });
96 this.performanceObserver.observe({ entryTypes: ['measure'] });
97 }
98
99 private logStatistics(): void {
100 logger.info(this.logPrefix() + ' %j', this.statistics);
101 }
102
103 private startDisplayInterval(): void {
104 if (Configuration.getStatisticsDisplayInterval() > 0) {
105 this.displayInterval = setInterval(() => {
106 this.logStatistics();
107 }, Configuration.getStatisticsDisplayInterval() * 1000);
108 logger.info(this.logPrefix() + ' displayed every ' + Utils.secondsToHHMMSS(Configuration.getStatisticsDisplayInterval()));
109 } else {
110 logger.info(this.logPrefix() + ' display interval is set to ' + Configuration.getStatisticsDisplayInterval().toString() + '. Not displaying statistics');
111 }
112 }
113
114 private median(dataSet: number[]): number {
115 if (Array.isArray(dataSet) && dataSet.length === 1) {
116 return dataSet[0];
117 }
118 const sortedDataSet = dataSet.slice().sort();
119 const middleIndex = Math.floor(sortedDataSet.length / 2);
120 if (sortedDataSet.length % 2) {
121 return sortedDataSet[middleIndex / 2];
122 }
123 return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2;
124 }
125
126 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
127 private percentile(dataSet: number[], percentile: number): number {
128 if (percentile < 0 && percentile > 100) {
129 throw new RangeError('Percentile is not between 0 and 100');
130 }
131 if (Utils.isEmptyArray(dataSet)) {
132 return 0;
133 }
134 const sortedDataSet = dataSet.slice().sort();
135 if (percentile === 0) {
136 return sortedDataSet[0];
137 }
138 if (percentile === 100) {
139 return sortedDataSet[sortedDataSet.length - 1];
140 }
141 const percentileIndex = ((percentile / 100) * sortedDataSet.length) - 1;
142 if (Number.isInteger(percentileIndex)) {
143 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
144 }
145 return sortedDataSet[Math.round(percentileIndex)];
146 }
147
148 private stdDeviation(dataSet: number[]): number {
149 let totalDataSet = 0;
150 for (const data of dataSet) {
151 totalDataSet += data;
152 }
153 const dataSetMean = totalDataSet / dataSet.length;
154 let totalGeometricDeviation = 0;
155 for (const data of dataSet) {
156 const deviation = data - dataSetMean;
157 totalGeometricDeviation += deviation * deviation;
158 }
159 return Math.sqrt(totalGeometricDeviation / dataSet.length);
160 }
161
162 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
163 let entryName = entry.name;
164 // Rename entry name
165 const MAP_NAME: Record<string, string> = {};
166 if (MAP_NAME[entryName]) {
167 entryName = MAP_NAME[entryName];
168 }
169 // Initialize command statistics
170 if (!this.statistics.statisticsData[entryName]) {
171 this.statistics.statisticsData[entryName] = {} as StatisticsData;
172 }
173 // Update current statistics
174 this.statistics.statisticsData[entryName].countTimeMeasurement = this.statistics.statisticsData[entryName].countTimeMeasurement ? this.statistics.statisticsData[entryName].countTimeMeasurement + 1 : 1;
175 this.statistics.statisticsData[entryName].currentTimeMeasurement = entry.duration;
176 this.statistics.statisticsData[entryName].minTimeMeasurement = this.statistics.statisticsData[entryName].minTimeMeasurement ? (this.statistics.statisticsData[entryName].minTimeMeasurement > entry.duration ? entry.duration : this.statistics.statisticsData[entryName].minTimeMeasurement) : entry.duration;
177 this.statistics.statisticsData[entryName].maxTimeMeasurement = this.statistics.statisticsData[entryName].maxTimeMeasurement ? (this.statistics.statisticsData[entryName].maxTimeMeasurement < entry.duration ? entry.duration : this.statistics.statisticsData[entryName].maxTimeMeasurement) : entry.duration;
178 this.statistics.statisticsData[entryName].totalTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement ? this.statistics.statisticsData[entryName].totalTimeMeasurement + entry.duration : entry.duration;
179 this.statistics.statisticsData[entryName].avgTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement / this.statistics.statisticsData[entryName].countTimeMeasurement;
180 Array.isArray(this.statistics.statisticsData[entryName].timeMeasurementSeries) ? this.statistics.statisticsData[entryName].timeMeasurementSeries.push(entry.duration) : this.statistics.statisticsData[entryName].timeMeasurementSeries = new CircularArray<number>(DEFAULT_CIRCULAR_ARRAY_SIZE, entry.duration);
181 this.statistics.statisticsData[entryName].medTimeMeasurement = this.median(this.statistics.statisticsData[entryName].timeMeasurementSeries);
182 this.statistics.statisticsData[entryName].ninetyFiveThPercentileTimeMeasurement = this.percentile(this.statistics.statisticsData[entryName].timeMeasurementSeries, 95);
183 this.statistics.statisticsData[entryName].stdDevTimeMeasurement = this.stdDeviation(this.statistics.statisticsData[entryName].timeMeasurementSeries);
184 }
185
186 private logPrefix(): string {
187 return Utils.logPrefix(` ${this.objId} | Performance statistics`);
188 }
189}