Quick.Chrono.pas 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. { ***************************************************************************
  2. Copyright (c) 2015-2019 Kike Pérez
  3. Unit : Quick.Chrono
  4. Description : Chronometers time elapsed and estimated time to do a task
  5. Author : Kike Pérez
  6. Version : 1.5
  7. Created : 27/08/2015
  8. Modified : 05/12/2019
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.Chrono;
  22. interface
  23. {$HPPEMIT LEGACYHPP}
  24. {$i QuickLib.inc}
  25. uses
  26. Classes,
  27. {$IF defined(MSWINDOWS)}
  28. Windows,
  29. {$ELSEIF defined(MACOS)}
  30. Macapi.Mach,
  31. {$ELSEIF defined(POSIX)}
  32. Posix.Time,
  33. {$ENDIF}
  34. {$IFDEF FPC}
  35. {$IFDEF LINUX}
  36. unixtype, linux,
  37. {$ENDIF}
  38. {$ELSE}
  39. System.TimeSpan,
  40. {$ENDIF}
  41. SysUtils,
  42. DateUtils;
  43. resourcestring
  44. strDAY = 'day';
  45. strHOUR = 'hour';
  46. strMINUTE = 'minute';
  47. strSECOND = 'second';
  48. strMILLISECOND = 'millisecond';
  49. strMICROSECOND = 'microsecond';
  50. strNANOSECOND = 'nanosecond';
  51. strFMTSHORT_HOURS_MINUTES = 'hh:nn:ss';
  52. strFMTSHORT_MINUTES_SECONDS = 'hh:nn:ss';
  53. strFMTLONG_HOURS_MINUTES = 'h "hour(s) and" n "minute(s)"';
  54. strFMTLONG_MINUTES_SECONDS = 'n "minute(s) and" s "second(s)"';
  55. type
  56. TTimeValue = (utDay, utHour, utMinute, utSecond, utMillisecond,utMicrosecond,utNanosecond);
  57. TTimeFmt = (tfHoursAndMinutes, tfMinutesAndSeconds);
  58. TPrecissionFormat = (pfFloat, pfRound, pfTruncate);
  59. const
  60. UnitShortTime : array[utDay..utNanosecond] of string = ('d','h','m','s','ms','μs','ns');
  61. UnitLongTime : array[utDay..utNanosecond] of string = (strDAY,strHOUR,strMINUTE,strSECOND,strMILLISECOND,strMICROSECOND,strNANOSECOND);
  62. FmtShortTime : array[tfHoursAndMinutes..tfMinutesAndSeconds] of string = (strFMTSHORT_HOURS_MINUTES,strFMTSHORT_MINUTES_SECONDS);
  63. FmtLongTime : array[tfHoursAndMinutes..tfMinutesAndSeconds] of string = (strFMTLONG_HOURS_MINUTES,strFMTLONG_MINUTES_SECONDS);
  64. {$IFDEF FPC}
  65. SecsPerHour = 3600;
  66. {$ENDIF}
  67. type
  68. TChronometer = class
  69. private
  70. fFrequency: Int64;
  71. fIsRunning: Boolean;
  72. fIsHighResolution: Boolean;
  73. fStartCount, fStopCount: Int64;
  74. fStartBreakPoint, fStopBreakPoint : Int64;
  75. fReportFormatPrecission : TPrecissionFormat;
  76. class function Precission(aValue : Extended; FormatPrecission : TPrecissionFormat) : Extended;
  77. function GetTickStamp : Int64;
  78. function GetElapsedTicks: Int64;
  79. function GetElapsedMilliseconds: Int64;
  80. function GetElapsedMillisecondsWithPrecission: Extended;
  81. function GetElapsedMilliseconds_BreakPoint: Int64;
  82. function GetElapsedMillisecondsWithPrecission_BreakPoint: Extended;
  83. function GetElapsedSeconds : Int64;
  84. class function GetUnitTime(TimeValue : TTimeValue; LongFormat : Boolean) : string;
  85. class function GetFmtTime(TimeFmt : TTimeFmt; LongFormat : Boolean) : string;
  86. public
  87. constructor Create(const StartOnCreate: Boolean = false);
  88. procedure Start;
  89. procedure Stop;
  90. procedure Reset;
  91. procedure Check;
  92. procedure BreakPoint;
  93. property IsHighResolution: Boolean read fIsHighResolution;
  94. property IsRunning: Boolean read fIsRunning;
  95. property ReportFormatPrecission: TPrecissionFormat read fReportFormatPrecission write fReportFormatPrecission;
  96. property ElapsedTicks: Int64 read GetElapsedTicks;
  97. property ElapsedMilliseconds: Int64 read GetElapsedMilliseconds;
  98. property ElapsedMilliseconds_Breakpoint: Int64 read GetElapsedMilliseconds_BreakPoint;
  99. property ElapsedMillisecondsWithPrecission: Extended read GetElapsedMillisecondsWithPrecission;
  100. property ElapsedMillisecondsWithPrecission_BreakPoint: Extended read GetElapsedMillisecondsWithPrecission_BreakPoint;
  101. property ElapsedSeconds: Int64 read GetElapsedSeconds;
  102. function ElapsedTime(LongFormat : Boolean = False) : string;
  103. function ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  104. class function MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string; overload;
  105. class function MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string; overload;
  106. end;
  107. TChronoBenchmark = class
  108. private
  109. fTotalProcess : Int64;
  110. fLastUpdateTime : TDateTime;
  111. fCurrentProcess : Int64;
  112. fFirstUpdateTime : TDateTime;
  113. fEstimatedMilliseconds : Int64;
  114. fSpeed : Single;
  115. procedure SetCurrentProcess(NewCurrentProcess : Int64);
  116. function GetElapsedMilliseconds : Int64;
  117. public
  118. constructor Create;
  119. property TotalProcess : Int64 read fTotalProcess write fTotalProcess;
  120. property CurrentProcess : Int64 read fCurrentProcess write SetCurrentProcess;
  121. property Speed : Single read fSpeed write fSpeed;
  122. property ElapsedMilliseconds : Int64 read GetElapsedMilliseconds;
  123. property EstimatedMilliseconds : Int64 read fEstimatedMilliseconds write fEstimatedMilliseconds;
  124. function ElapsedTime(LongFormat : Boolean) : string;
  125. function EstimatedTime(LongFormat : Boolean) : string;
  126. procedure Reset;
  127. end;
  128. implementation
  129. { TChronometer Class }
  130. constructor TChronometer.Create(const StartOnCreate: Boolean = false);
  131. begin
  132. inherited Create;
  133. fIsRunning := False;
  134. fReportFormatPrecission := pfFloat;
  135. fStartCount := 0;
  136. fStopCount := 0;
  137. fStartBreakPoint := 0;
  138. fStopBreakPoint := 0;
  139. {$IF Defined(MSWINDOWS)}
  140. if not QueryPerformanceFrequency(fFrequency) then
  141. begin
  142. fIsHighResolution := False;
  143. //fFrequency := TTimeSpan.TicksPerSecond;
  144. fFrequency := MSecsPerSec;
  145. //TickFrequency := 1.0;
  146. end else
  147. begin
  148. fIsHighResolution := True;
  149. //TickFrequency := 10000000.0 / fFrequency;
  150. end;
  151. {$ELSEIF Defined(POSIX) OR Defined(LINUX)}
  152. fIsHighResolution := True;
  153. fFrequency := 10000000;
  154. //TickFrequency := 10000000.0 / fFrequency;
  155. {$ENDIF}
  156. if StartOnCreate then Start;
  157. end;
  158. function TChronometer.GetElapsedTicks: Int64;
  159. begin
  160. Result := fStopCount - fStartCount;
  161. end;
  162. function TChronometer.GetTickStamp : Int64;
  163. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  164. var
  165. res: timespec;
  166. {$ENDIF}
  167. begin
  168. {$IFDEF MSWINDOWS}
  169. if fIsHighResolution then QueryPerformanceCounter(Result)
  170. else Result := MilliSecondOf(Now);
  171. {$ELSE}
  172. {$IFDEF MACOS}
  173. Result := Int64(AbsoluteToNanoseconds(mach_absolute_time) div 100);
  174. {$ENDIF}
  175. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  176. clock_gettime(CLOCK_MONOTONIC, @res);
  177. Result := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 100;
  178. {$ENDIF}
  179. {$ENDIF}
  180. end;
  181. function TChronometer.ElapsedTime(LongFormat : Boolean = False) : string;
  182. begin
  183. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission,fReportFormatPrecission,LongFormat);
  184. end;
  185. function TChronometer.ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  186. begin
  187. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission_BreakPoint,fReportFormatPrecission,True);
  188. end;
  189. class function TChronometer.GetUnitTime(TimeValue : TTimeValue; LongFormat : Boolean) : string;
  190. begin
  191. if LongFormat then Result := ' ' + UnitLongTime[TimeValue] + '(s)'
  192. else Result := UnitShortTime[TimeValue];
  193. end;
  194. class function TChronometer.GetFmtTime(TimeFmt : TTimeFmt; LongFormat : Boolean) : string;
  195. begin
  196. if LongFormat then Result := FmtLongTime[TimeFmt]
  197. else Result := FmtShortTime[TimeFmt];
  198. end;
  199. class function TChronometer.MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string;
  200. begin
  201. Result := MillisecondsToString(aMilliseconds.ToExtended,pfTruncate,LongFormat);
  202. end;
  203. class function TChronometer.Precission(aValue : Extended; FormatPrecission : TPrecissionFormat) : Extended;
  204. begin
  205. case FormatPrecission of
  206. pfRound : Result := Round(aValue).ToExtended;
  207. pfTruncate : Result := Int(aValue);
  208. else Result := aValue;
  209. end;
  210. end;
  211. class function TChronometer.MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string;
  212. var
  213. dt : TDateTime;
  214. mc : Extended;
  215. begin
  216. if aMilliseconds < 1.0 then
  217. begin
  218. mc := frac(aMilliseconds) * 1000;
  219. if Int(mc) = 0 then Result := Format('%d%s',[Trunc(frac(mc) * 1000),GetUnitTime(utNanosecond,LongFormat)]) //nanoseconds
  220. else Result := Format('%d%s',[Trunc(mc),GetUnitTime(utMicrosecond,LongFormat)]); //microseconds
  221. end
  222. else
  223. begin
  224. if aMilliseconds < MSecsPerSec then //milliseconds
  225. begin
  226. aMilliseconds := Precission(aMilliseconds,FormatPrecission);
  227. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMillisecond,LongFormat)])
  228. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMillisecond,LongFormat)])
  229. end
  230. else if (aMilliseconds / MSecsPerSec) < SecsPerMin then //seconds
  231. begin
  232. aMilliseconds := Precission((aMilliseconds / MSecsPerSec),FormatPrecission);
  233. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utSecond,LongFormat)])
  234. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utSecond,LongFormat)]);
  235. end
  236. else if ((aMilliseconds / MSecsPerSec) < SecsPerHour) and ((Round(aMilliseconds) mod (SecsPerMin * MSecsPerSec)) = 0) then //minutes
  237. begin
  238. aMilliseconds := Precission((aMilliseconds / (SecsPerMin * MSecsPerSec)),FormatPrecission);
  239. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMinute,LongFormat)])
  240. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMinute,LongFormat)])
  241. end
  242. else if (aMilliseconds / MSecsPerSec) < SecsPerDay then //hours
  243. begin
  244. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  245. if LongFormat then
  246. begin
  247. if (aMilliseconds / MSecsPerSec) > SecsPerHour then Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))
  248. else Result := FormatDateTime(GetFmtTime(tfMinutesAndSeconds,LongFormat),Frac(dt));
  249. end
  250. else
  251. begin
  252. Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt));
  253. end;
  254. end
  255. else //días
  256. begin
  257. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  258. Result := Format('%d%s, %s', [trunc(dt),GetUnitTime(utDay,LongFormat),FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))]);
  259. end;
  260. end;
  261. end;
  262. function TChronometer.GetElapsedMilliseconds : Int64;
  263. begin
  264. result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
  265. end;
  266. function TChronometer.GetElapsedMilliseconds_BreakPoint : Int64;
  267. begin
  268. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) div fFrequency;
  269. end;
  270. function TChronometer.GetElapsedMillisecondsWithPrecission : Extended;
  271. begin
  272. result := (MSecsPerSec * (fStopCount - fStartCount)) / fFrequency;
  273. end;
  274. function TChronometer.GetElapsedMillisecondsWithPrecission_BreakPoint : Extended;
  275. begin
  276. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) / fFrequency;
  277. end;
  278. function TChronometer.GetElapsedSeconds : Int64;
  279. begin
  280. result := ((MSecsPerSec * (fStopCount - fStartCount)) div fFrequency) div MSecsPerSec;
  281. end;
  282. procedure TChronometer.Start;
  283. begin
  284. fStartCount := GetTickStamp;
  285. fIsRunning := true;
  286. end;
  287. procedure TChronometer.Stop;
  288. begin
  289. fStopCount := GetTickStamp;
  290. fIsRunning := false;
  291. end;
  292. procedure TChronometer.Reset;
  293. begin
  294. fStartCount := GetTickStamp;
  295. end;
  296. procedure TChronometer.Check;
  297. begin
  298. if fIsRunning then fStopCount := GetTickStamp;
  299. end;
  300. procedure TChronometer.BreakPoint;
  301. begin
  302. if fIsRunning then
  303. begin
  304. if fStartBreakPoint = 0 then
  305. begin
  306. fStopBreakPoint := GetTickStamp;
  307. fStartBreakPoint := fStartCount;
  308. end
  309. else
  310. begin
  311. fStartBreakPoint := fStopBreakPoint;
  312. fStopBreakPoint := GetTickStamp;
  313. end;
  314. end
  315. else fStopBreakPoint := fStopCount;
  316. end;
  317. { TChronoBenchmark Class }
  318. constructor TChronoBenchmark.Create;
  319. begin
  320. inherited;
  321. fTotalProcess := 0;
  322. fSpeed := 0;
  323. fLastUpdateTime := Now();
  324. fCurrentProcess := 0;
  325. fFirstUpdateTime := 0;
  326. fEstimatedMilliseconds := 0;
  327. end;
  328. procedure TChronoBenchmark.SetCurrentProcess(NewCurrentProcess : Int64);
  329. begin
  330. //corrects first time run
  331. if fLastUpdateTime = 0 then fLastUpdateTime := Now();
  332. if fFirstUpdateTime = 0 then fFirstUpdateTime := Now();
  333. //calculates operation speed
  334. fSpeed := (NewCurrentProcess - fCurrentProcess) / ((Now() - fLastUpdateTime) * 86400);
  335. if fSpeed = 0 then fSpeed := 0.1;
  336. //returns estimated time string
  337. fEstimatedMilliseconds := Round(((TotalProcess - NewCurrentProcess) / fSpeed) * 1000);
  338. //save current values
  339. fLastUpdateTime := Now();
  340. fCurrentProcess := NewCurrentProcess;
  341. end;
  342. function TChronoBenchmark.GetElapsedMilliseconds : Int64;
  343. begin
  344. Result := Round(((Now() - fFirstUpdateTime) * 86400 * 1000));
  345. end;
  346. function TChronoBenchmark.ElapsedTime(LongFormat : Boolean) : string;
  347. begin
  348. Result := TChronometer.MillisecondsToString(GetElapsedMilliseconds,LongFormat);
  349. end;
  350. function TChronoBenchmark.EstimatedTime(LongFormat : Boolean) : string;
  351. begin
  352. Result := TChronometer.MillisecondsToString(fEstimatedMilliseconds,LongFormat);
  353. end;
  354. procedure TChronoBenchmark.Reset;
  355. begin
  356. fLastUpdateTime := Now();
  357. fSpeed := 0;
  358. fCurrentProcess := 0;
  359. fFirstUpdateTime := 0;
  360. fEstimatedMilliseconds := 0;
  361. end;
  362. end.