Agrarsense
SimpleTimer.h
Go to the documentation of this file.
1// Copyright (c) 2023 FrostBit Software Lab at the Lapland University of Applied Sciences
2//
3// This work is licensed under the terms of the MIT license.
4// For a copy, see <https://opensource.org/licenses/MIT>.
5
6#pragma once
7
8#include "Engine/GameEngine.h"
9#include "Containers/UnrealString.h"
10#include "CoreMinimal.h"
11
50{
51
52public:
53
58 {
60 }
61
65 void Reset()
66 {
68
70 counter = 0;
71 }
72
77 {
78 startTime = FPlatformTime::Seconds();
79 }
80
87 void StopTimer(FString prefix = "Code executed in ", FString suffix = " milliseconds", bool printToScreen = false)
88 {
89 double endTime = FPlatformTime::Seconds();
90 float milliseconds = (endTime - startTime) * 1000;
91
92 FString msString = FString::SanitizeFloat(milliseconds);
93 FString msg = prefix + msString + suffix;
94 UE_LOG(LogTemp, Warning, TEXT("%s"), *msg);
95
96 if (GEngine && printToScreen)
97 {
98 GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf(TEXT("%s"), *msg));
99 }
100 }
101
106 {
107 double endTime = FPlatformTime::Seconds();
108 float milliseconds = (endTime - startTime) * 1000;
109
110 totalMilliseconds += milliseconds;
111 ++counter;
112 double currentAvg = totalMilliseconds / counter;
113
114 return currentAvg;
115 }
116
123 double PrintAverageTime(FString prefix = "Average execution time ", FString suffix = " milliseconds", bool printToScreen = false)
124 {
125 double currentAvg = GetAverageTime();
126
127 FString msString = FString::SanitizeFloat(currentAvg);
128 FString msg = prefix + msString + suffix;
129
130#if WITH_EDITOR
131 UE_LOG(LogTemp, Warning, TEXT("%s"), *msg);
132 if (GEngine && printToScreen)
133 {
134 GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf(TEXT("%s"), *msg));
135 }
136#endif
137
138 return currentAvg;
139 }
140
142 {
143 totalMilliseconds = 0.0;
144 counter = 0;
145 }
146
147private:
148
149 double startTime;
150 double totalMilliseconds = 0.0;
151 int counter = 0;
152
153};
double GetAverageTime()
Definition: SimpleTimer.h:105
void StopTimer(FString prefix="Code executed in ", FString suffix=" milliseconds", bool printToScreen=false)
Definition: SimpleTimer.h:87
double totalMilliseconds
Definition: SimpleTimer.h:150
double startTime
Definition: SimpleTimer.h:149
double PrintAverageTime(FString prefix="Average execution time ", FString suffix=" milliseconds", bool printToScreen=false)
Definition: SimpleTimer.h:123
void TakeTimeStamp()
Definition: SimpleTimer.h:76
void Reset()
Definition: SimpleTimer.h:65
void ResetAverageTime()
Definition: SimpleTimer.h:141