Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timer Utility Class #1054

Merged
merged 1 commit into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions project/src/servers/SaveServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { LocalisationService } from "@spt/services/LocalisationService";
import { FileSystemSync } from "@spt/utils/FileSystemSync";
import { HashUtil } from "@spt/utils/HashUtil";
import { JsonUtil } from "@spt/utils/JsonUtil";
import { Timer } from "@spt/utils/Timer";
import { inject, injectAll, injectable } from "tsyringe";

@injectable()
Expand Down Expand Up @@ -55,28 +56,26 @@ export class SaveServer {
const files = this.fileSystemSync.getFiles(this.profileFilepath, false, ["json"]);

// load profiles
const start = performance.now();
let loadTimeCount = 0;
const timer = new Timer();
for (const file of files) {
this.loadProfile(FileSystemSync.getFileName(file));
loadTimeCount += performance.now() - start;
}

this.logger.debug(`${files.length} Profiles took: ${loadTimeCount.toFixed(2)}ms to load.`);
this.logger.debug(
`Loading ${files.length} profile${files.length > 1 ? "s" : ""} took ${timer.getTime("ms")}ms`,
);
}

/**
* Save changes for each profile from memory into user/profiles json
*/
public save(): void {
// Save every profile
let totalTime = 0;
const timer = new Timer();
for (const sessionID in this.profiles) {
totalTime += this.saveProfile(sessionID);
this.saveProfile(sessionID);
}

const profileCount = Object.keys(this.profiles).length;
this.logger.debug(
`Saved ${Object.keys(this.profiles).length} profiles, took: ${totalTime.toFixed(2)}ms`,
`Saving ${profileCount} profile${profileCount > 1 ? "s" : ""} took ${timer.getTime("ms")}ms`,
false,
);
}
Expand Down Expand Up @@ -171,9 +170,9 @@ export class SaveServer {
* Save changes from in-memory profile to user/profiles json
* Execute onBeforeSaveCallbacks callbacks prior to being saved to json
* @param sessionID profile id (user/profiles/id.json)
* @returns time taken to save in MS
* @returns void
*/
public saveProfile(sessionID: string): number {
public saveProfile(sessionID: string): void {
const filePath = `${this.profileFilepath}${sessionID}.json`;

// Run pre-save callbacks before we save into json
Expand All @@ -187,7 +186,6 @@ export class SaveServer {
}
}

const start = performance.now();
const jsonProfile = this.jsonUtil.serialize(
this.profiles[sessionID],
!this.configServer.getConfig<ICoreConfig>(ConfigTypes.CORE).features.compressProfile,
Expand All @@ -198,8 +196,6 @@ export class SaveServer {
// save profile to disk
this.fileSystemSync.write(filePath, jsonProfile);
}

return Number(performance.now() - start);
}

/**
Expand Down
7 changes: 3 additions & 4 deletions project/src/services/DatabaseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type { ILogger } from "@spt/models/spt/utils/ILogger";
import { DatabaseServer } from "@spt/servers/DatabaseServer";
import { LocalisationService } from "@spt/services/LocalisationService";
import { HashUtil } from "@spt/utils/HashUtil";
import { Timer } from "@spt/utils/Timer";
import { inject, injectable } from "tsyringe";

@injectable()
Expand Down Expand Up @@ -333,8 +334,7 @@ export class DatabaseService {
* Validates that the database doesn't contain invalid ID data
*/
public validateDatabase(): void {
const start = performance.now();

const timer = new Timer();
this.isDataValid =
this.validateTable(this.getQuests(), "quest") &&
this.validateTable(this.getTraders(), "trader") &&
Expand All @@ -345,8 +345,7 @@ export class DatabaseService {
this.logger.error(this.localisationService.getText("database-invalid_data"));
}

const validateTime = performance.now() - start;
this.logger.debug(`ID validation took: ${validateTime.toFixed(2)}ms`);
this.logger.debug(`Database ID validation took ${timer.getTime("ms")}ms`);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions project/src/services/ProfileFixerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { LocalisationService } from "@spt/services/LocalisationService";
import { HashUtil } from "@spt/utils/HashUtil";
import { JsonUtil } from "@spt/utils/JsonUtil";
import { TimeUtil } from "@spt/utils/TimeUtil";
import { Timer } from "@spt/utils/Timer";
import { Watermark } from "@spt/utils/Watermark";
import type { ICloner } from "@spt/utils/cloners/ICloner";
import { inject, injectable } from "tsyringe";
Expand Down Expand Up @@ -308,7 +309,7 @@ export class ProfileFixerService {
* @param pmcProfile The profile to validate quest productions for
*/
protected verifyQuestProductionUnlocks(pmcProfile: IPmcData): void {
const start = performance.now();
const timer = new Timer();

const quests = this.databaseService.getQuests();
const profileQuests = pmcProfile.Quests;
Expand Down Expand Up @@ -336,8 +337,7 @@ export class ProfileFixerService {
}
}

const validateTime = performance.now() - start;
this.logger.debug(`Quest Production Unlock validation took: ${validateTime.toFixed(2)}ms`);
this.logger.debug(`Quest production unlock validation took ${timer.getTime("ms")}ms`);
}

/**
Expand Down
5 changes: 5 additions & 0 deletions project/src/utils/DatabaseImporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { HashUtil } from "@spt/utils/HashUtil";
import { ImporterUtil } from "@spt/utils/ImporterUtil";
import { JsonUtil } from "@spt/utils/JsonUtil";
import { inject, injectable } from "tsyringe";
import { Timer } from "./Timer";

@injectable()
export class DatabaseImporter implements OnLoad {
Expand Down Expand Up @@ -81,6 +82,7 @@ export class DatabaseImporter implements OnLoad {
*/
protected async hydrateDatabase(filepath: string): Promise<void> {
this.logger.info(this.localisationService.getText("importing_database"));
const timer = new Timer();

const dataToImport = await this.importerUtil.loadAsync<IDatabaseTables>(
`${filepath}database/`,
Expand All @@ -90,7 +92,10 @@ export class DatabaseImporter implements OnLoad {

const validation =
this.valid === VaildationResult.FAILED || this.valid === VaildationResult.NOT_FOUND ? "." : "";

this.logger.info(`${this.localisationService.getText("importing_database_finish")}${validation}`);
this.logger.debug(`Database import took ${timer.getTime("sec")}s`);

this.databaseServer.setTables(dataToImport);
}

Expand Down
33 changes: 33 additions & 0 deletions project/src/utils/Timer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
export class Timer {
private startTime: bigint = process.hrtime.bigint();

/**
* Resets the timer to its initial state.
*/
public restart(): void {
this.startTime = process.hrtime.bigint();
}

/**
* Returns the elapsed time in the specified unit with up to four decimal places of precision for ms and sec.
*
* @param unit The desired unit for the elapsed time ("ns", "ms", "sec").
* @returns The elapsed time in the specified unit.
*/
public getTime(unit: "ns" | "ms" | "sec"): number {
const elapsedTime = process.hrtime.bigint() - this.startTime;

switch (unit) {
case "ns":
return Number(elapsedTime);
case "ms": {
const ms = Number(elapsedTime) / 1_000_000;
return Number(ms.toFixed(3));
}
default: {
const sec = Number(elapsedTime) / 1_000_000_000;
return Number(sec.toFixed(4));
}
}
}
}
Loading