Quick.Chrono.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. { ***************************************************************************
  2. Copyright (c) 2015-2021 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 : 06/05/2021
  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. {$IFDEF DELPHIXE7_UP}
  24. {$HPPEMIT LEGACYHPP}
  25. {$ENDIF}
  26. {$i QuickLib.inc}
  27. uses
  28. Classes,
  29. {$IF defined(MSWINDOWS)}
  30. Windows,
  31. {$ELSEIF defined(MACOS)}
  32. Macapi.Mach,
  33. {$ELSEIF defined(POSIX)}
  34. Posix.Time,
  35. {$ENDIF}
  36. {$IFDEF FPC}
  37. {$IFDEF LINUX}
  38. unixtype, linux,
  39. {$ENDIF}
  40. {$ELSE}
  41. System.TimeSpan,
  42. {$ENDIF}
  43. SysUtils,
  44. DateUtils;
  45. resourcestring
  46. strDAY = 'day';
  47. strHOUR = 'hour';
  48. strMINUTE = 'minute';
  49. strSECOND = 'second';
  50. strMILLISECOND = 'millisecond';
  51. strMICROSECOND = 'microsecond';
  52. strNANOSECOND = 'nanosecond';
  53. strFMTSHORT_HOURS_MINUTES = 'hh:nn:ss';
  54. strFMTSHORT_MINUTES_SECONDS = 'hh:nn:ss';
  55. strFMTLONG_HOURS_MINUTES = 'h "hour(s) and" n "minute(s)"';
  56. strFMTLONG_MINUTES_SECONDS = 'n "minute(s) and" s "second(s)"';
  57. type
  58. TTimeValue = (utDay, utHour, utMinute, utSecond, utMillisecond,utMicrosecond,utNanosecond);
  59. TTimeFmt = (tfHoursAndMinutes, tfMinutesAndSeconds);
  60. TPrecissionFormat = (pfFloat, pfRound, pfTruncate);
  61. const
  62. UnitShortTime : array[utDay..utNanosecond] of string = ('d','h','m','s','ms','μs','ns');
  63. UnitLongTime : array[utDay..utNanosecond] of string = (strDAY,strHOUR,strMINUTE,strSECOND,strMILLISECOND,strMICROSECOND,strNANOSECOND);
  64. FmtShortTime : array[tfHoursAndMinutes..tfMinutesAndSeconds] of string = (strFMTSHORT_HOURS_MINUTES,strFMTSHORT_MINUTES_SECONDS);
  65. FmtLongTime : array[tfHoursAndMinutes..tfMinutesAndSeconds] of string = (strFMTLONG_HOURS_MINUTES,strFMTLONG_MINUTES_SECONDS);
  66. {$IFDEF FPC}
  67. SecsPerHour = 3600;
  68. {$ENDIF}
  69. type
  70. IChronometer = interface
  71. ['{F742C1AD-69DF-4EAA-AB0D-6E571C887901}']
  72. function GetIsRunning : Boolean;
  73. function GetElapsedTicks: Int64;
  74. function GetElapsedMilliseconds: Int64;
  75. function GetElapsedMillisecondsWithPrecission: Extended;
  76. function GetElapsedMilliseconds_BreakPoint: Int64;
  77. function GetElapsedMillisecondsWithPrecission_BreakPoint: Extended;
  78. function GetElapsedSeconds : Int64;
  79. property IsRunning: Boolean read GetIsRunning;
  80. procedure Start;
  81. procedure Stop;
  82. procedure Reset;
  83. procedure Check;
  84. procedure BreakPoint;
  85. property ElapsedTicks: Int64 read GetElapsedTicks;
  86. property ElapsedMilliseconds: Int64 read GetElapsedMilliseconds;
  87. property ElapsedMilliseconds_Breakpoint: Int64 read GetElapsedMilliseconds_BreakPoint;
  88. property ElapsedMillisecondsWithPrecission: Extended read GetElapsedMillisecondsWithPrecission;
  89. property ElapsedMillisecondsWithPrecission_BreakPoint: Extended read GetElapsedMillisecondsWithPrecission_BreakPoint;
  90. property ElapsedSeconds: Int64 read GetElapsedSeconds;
  91. function ElapsedTime(LongFormat : Boolean = False) : string;
  92. function ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  93. end;
  94. TChronometer = class(TInterfacedObject,IChronometer)
  95. private
  96. fFrequency: Int64;
  97. fIsRunning: Boolean;
  98. fIsHighResolution: Boolean;
  99. fStartCount, fStopCount: Int64;
  100. fStartBreakPoint, fStopBreakPoint : Int64;
  101. fReportFormatPrecission : TPrecissionFormat;
  102. class function Precission(aValue : Extended; FormatPrecission : TPrecissionFormat) : Extended;
  103. function GetTickStamp : Int64;
  104. function GetElapsedTicks: Int64;
  105. function GetElapsedMilliseconds: Int64;
  106. function GetElapsedMillisecondsWithPrecission: Extended;
  107. function GetElapsedMilliseconds_BreakPoint: Int64;
  108. function GetElapsedMillisecondsWithPrecission_BreakPoint: Extended;
  109. function GetElapsedSeconds : Int64;
  110. class function GetUnitTime(TimeValue : TTimeValue; LongFormat : Boolean) : string;
  111. class function GetFmtTime(TimeFmt : TTimeFmt; LongFormat : Boolean) : string;
  112. function GetIsRunning: Boolean;
  113. public
  114. constructor Create(const StartOnCreate: Boolean = false);
  115. class function NewChrono(const StartOnCreate: Boolean = True) : IChronometer;
  116. procedure Start;
  117. procedure Stop;
  118. procedure Reset;
  119. procedure Check;
  120. procedure BreakPoint;
  121. property IsHighResolution: Boolean read fIsHighResolution;
  122. property IsRunning: Boolean read GetIsRunning;
  123. property ReportFormatPrecission: TPrecissionFormat read fReportFormatPrecission write fReportFormatPrecission;
  124. property ElapsedTicks: Int64 read GetElapsedTicks;
  125. property ElapsedMilliseconds: Int64 read GetElapsedMilliseconds;
  126. property ElapsedMilliseconds_Breakpoint: Int64 read GetElapsedMilliseconds_BreakPoint;
  127. property ElapsedMillisecondsWithPrecission: Extended read GetElapsedMillisecondsWithPrecission;
  128. property ElapsedMillisecondsWithPrecission_BreakPoint: Extended read GetElapsedMillisecondsWithPrecission_BreakPoint;
  129. property ElapsedSeconds: Int64 read GetElapsedSeconds;
  130. function ElapsedTime(LongFormat : Boolean = False) : string;
  131. function ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  132. class function MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string; overload;
  133. class function MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string; overload;
  134. end;
  135. TChronoBenchmark = class
  136. private
  137. fTotalProcess : Int64;
  138. fLastUpdateTime : TDateTime;
  139. fCurrentProcess : Int64;
  140. fFirstUpdateTime : TDateTime;
  141. fEstimatedMilliseconds : Int64;
  142. fSpeed : Single;
  143. procedure SetCurrentProcess(NewCurrentProcess : Int64);
  144. function GetElapsedMilliseconds : Int64;
  145. public
  146. constructor Create;
  147. property TotalProcess : Int64 read fTotalProcess write fTotalProcess;
  148. property CurrentProcess : Int64 read fCurrentProcess write SetCurrentProcess;
  149. property Speed : Single read fSpeed write fSpeed;
  150. property ElapsedMilliseconds : Int64 read GetElapsedMilliseconds;
  151. property EstimatedMilliseconds : Int64 read fEstimatedMilliseconds write fEstimatedMilliseconds;
  152. function ElapsedTime(LongFormat : Boolean) : string;
  153. function EstimatedTime(LongFormat : Boolean) : string;
  154. procedure Reset;
  155. end;
  156. implementation
  157. { TChronometer Class }
  158. constructor TChronometer.Create(const StartOnCreate: Boolean = false);
  159. begin
  160. inherited Create;
  161. fIsRunning := False;
  162. fReportFormatPrecission := pfFloat;
  163. fStartCount := 0;
  164. fStopCount := 0;
  165. fStartBreakPoint := 0;
  166. fStopBreakPoint := 0;
  167. {$IF Defined(MSWINDOWS)}
  168. if not QueryPerformanceFrequency(fFrequency) then
  169. begin
  170. fIsHighResolution := False;
  171. //fFrequency := TTimeSpan.TicksPerSecond;
  172. fFrequency := MSecsPerSec;
  173. //TickFrequency := 1.0;
  174. end else
  175. begin
  176. fIsHighResolution := True;
  177. //TickFrequency := 10000000.0 / fFrequency;
  178. end;
  179. {$ELSEIF Defined(POSIX) OR Defined(LINUX)}
  180. fIsHighResolution := True;
  181. fFrequency := 10000000;
  182. //TickFrequency := 10000000.0 / fFrequency;
  183. {$ENDIF}
  184. if StartOnCreate then Start;
  185. end;
  186. function TChronometer.GetElapsedTicks: Int64;
  187. begin
  188. Result := fStopCount - fStartCount;
  189. end;
  190. function TChronometer.GetTickStamp : Int64;
  191. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  192. var
  193. res: timespec;
  194. {$ENDIF}
  195. begin
  196. {$IFDEF MSWINDOWS}
  197. if fIsHighResolution then QueryPerformanceCounter(Result)
  198. else Result := MilliSecondOf(Now);
  199. {$ELSE}
  200. {$IFDEF MACOS}
  201. Result := Int64(AbsoluteToNanoseconds(mach_absolute_time) div 100);
  202. {$ENDIF}
  203. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  204. clock_gettime(CLOCK_MONOTONIC, @res);
  205. Result := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 100;
  206. {$ENDIF}
  207. {$ENDIF}
  208. end;
  209. function TChronometer.ElapsedTime(LongFormat : Boolean = False) : string;
  210. begin
  211. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission,fReportFormatPrecission,LongFormat);
  212. end;
  213. function TChronometer.ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  214. begin
  215. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission_BreakPoint,fReportFormatPrecission,LongFormat);
  216. end;
  217. class function TChronometer.GetUnitTime(TimeValue : TTimeValue; LongFormat : Boolean) : string;
  218. begin
  219. if LongFormat then Result := ' ' + UnitLongTime[TimeValue] + '(s)'
  220. else Result := UnitShortTime[TimeValue];
  221. end;
  222. class function TChronometer.GetFmtTime(TimeFmt : TTimeFmt; LongFormat : Boolean) : string;
  223. begin
  224. if LongFormat then Result := FmtLongTime[TimeFmt]
  225. else Result := FmtShortTime[TimeFmt];
  226. end;
  227. function TChronometer.GetIsRunning: Boolean;
  228. begin
  229. Result := fIsRunning;
  230. end;
  231. class function TChronometer.NewChrono(const StartOnCreate: Boolean = True) : IChronometer;
  232. begin
  233. Result := TChronometer.Create(StartOnCreate);
  234. end;
  235. class function TChronometer.MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string;
  236. begin
  237. Result := MillisecondsToString(aMilliseconds.ToExtended,pfTruncate,LongFormat);
  238. end;
  239. class function TChronometer.Precission(aValue : Extended; FormatPrecission : TPrecissionFormat) : Extended;
  240. begin
  241. case FormatPrecission of
  242. pfRound : Result := Round(aValue).ToExtended;
  243. pfTruncate : Result := Int(aValue);
  244. else Result := aValue;
  245. end;
  246. end;
  247. class function TChronometer.MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string;
  248. var
  249. dt : TDateTime;
  250. mc : Extended;
  251. begin
  252. if aMilliseconds < 1.0 then
  253. begin
  254. mc := frac(aMilliseconds) * 1000;
  255. if Int(mc) = 0 then Result := Format('%d%s',[Trunc(frac(mc) * 1000),GetUnitTime(utNanosecond,LongFormat)]) //nanoseconds
  256. else Result := Format('%d%s',[Trunc(mc),GetUnitTime(utMicrosecond,LongFormat)]); //microseconds
  257. end
  258. else
  259. begin
  260. if aMilliseconds < MSecsPerSec then //milliseconds
  261. begin
  262. aMilliseconds := Precission(aMilliseconds,FormatPrecission);
  263. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMillisecond,LongFormat)])
  264. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMillisecond,LongFormat)])
  265. end
  266. else if (aMilliseconds / MSecsPerSec) < SecsPerMin then //seconds
  267. begin
  268. aMilliseconds := Precission((aMilliseconds / MSecsPerSec),FormatPrecission);
  269. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utSecond,LongFormat)])
  270. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utSecond,LongFormat)]);
  271. end
  272. else if ((aMilliseconds / MSecsPerSec) < SecsPerHour) and ((Round(aMilliseconds) mod (SecsPerMin * MSecsPerSec)) = 0) then //minutes
  273. begin
  274. aMilliseconds := Precission((aMilliseconds / (SecsPerMin * MSecsPerSec)),FormatPrecission);
  275. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMinute,LongFormat)])
  276. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMinute,LongFormat)])
  277. end
  278. else if (aMilliseconds / MSecsPerSec) < SecsPerDay then //hours
  279. begin
  280. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  281. if LongFormat then
  282. begin
  283. if (aMilliseconds / MSecsPerSec) > SecsPerHour then Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))
  284. else Result := FormatDateTime(GetFmtTime(tfMinutesAndSeconds,LongFormat),Frac(dt));
  285. end
  286. else
  287. begin
  288. Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt));
  289. end;
  290. end
  291. else //días
  292. begin
  293. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  294. Result := Format('%d%s, %s', [trunc(dt),GetUnitTime(utDay,LongFormat),FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))]);
  295. end;
  296. end;
  297. end;
  298. function TChronometer.GetElapsedMilliseconds : Int64;
  299. begin
  300. result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
  301. end;
  302. function TChronometer.GetElapsedMilliseconds_BreakPoint : Int64;
  303. begin
  304. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) div fFrequency;
  305. end;
  306. function TChronometer.GetElapsedMillisecondsWithPrecission : Extended;
  307. begin
  308. result := (MSecsPerSec * (fStopCount - fStartCount)) / fFrequency;
  309. end;
  310. function TChronometer.GetElapsedMillisecondsWithPrecission_BreakPoint : Extended;
  311. begin
  312. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) / fFrequency;
  313. end;
  314. function TChronometer.GetElapsedSeconds : Int64;
  315. begin
  316. result := ((MSecsPerSec * (fStopCount - fStartCount)) div fFrequency) div MSecsPerSec;
  317. end;
  318. procedure TChronometer.Start;
  319. begin
  320. fStartCount := GetTickStamp;
  321. fIsRunning := true;
  322. end;
  323. procedure TChronometer.Stop;
  324. begin
  325. fStopCount := GetTickStamp;
  326. fIsRunning := false;
  327. end;
  328. procedure TChronometer.Reset;
  329. begin
  330. fStartCount := GetTickStamp;
  331. end;
  332. procedure TChronometer.Check;
  333. begin
  334. if fIsRunning then fStopCount := GetTickStamp;
  335. end;
  336. procedure TChronometer.BreakPoint;
  337. begin
  338. if fIsRunning then
  339. begin
  340. if fStartBreakPoint = 0 then
  341. begin
  342. fStopBreakPoint := GetTickStamp;
  343. fStartBreakPoint := fStartCount;
  344. end
  345. else
  346. begin
  347. fStartBreakPoint := fStopBreakPoint;
  348. fStopBreakPoint := GetTickStamp;
  349. end;
  350. end
  351. else fStopBreakPoint := fStopCount;
  352. end;
  353. { TChronoBenchmark Class }
  354. constructor TChronoBenchmark.Create;
  355. begin
  356. inherited;
  357. fTotalProcess := 0;
  358. fSpeed := 0;
  359. fLastUpdateTime := Now();
  360. fCurrentProcess := 0;
  361. fFirstUpdateTime := 0;
  362. fEstimatedMilliseconds := 0;
  363. end;
  364. procedure TChronoBenchmark.SetCurrentProcess(NewCurrentProcess : Int64);
  365. begin
  366. //corrects first time run
  367. if fLastUpdateTime = 0 then fLastUpdateTime := Now();
  368. if fFirstUpdateTime = 0 then fFirstUpdateTime := Now();
  369. //calculates operation speed
  370. fSpeed := (NewCurrentProcess - fCurrentProcess) / ((Now() - fLastUpdateTime) * 86400);
  371. if fSpeed = 0 then fSpeed := 0.1;
  372. //returns estimated time string
  373. fEstimatedMilliseconds := Round(((TotalProcess - NewCurrentProcess) / fSpeed) * 1000);
  374. //save current values
  375. fLastUpdateTime := Now();
  376. fCurrentProcess := NewCurrentProcess;
  377. end;
  378. function TChronoBenchmark.GetElapsedMilliseconds : Int64;
  379. begin
  380. Result := Round(((Now() - fFirstUpdateTime) * 86400 * 1000));
  381. end;
  382. function TChronoBenchmark.ElapsedTime(LongFormat : Boolean) : string;
  383. begin
  384. Result := TChronometer.MillisecondsToString(GetElapsedMilliseconds,LongFormat);
  385. end;
  386. function TChronoBenchmark.EstimatedTime(LongFormat : Boolean) : string;
  387. begin
  388. Result := TChronometer.MillisecondsToString(fEstimatedMilliseconds,LongFormat);
  389. end;
  390. procedure TChronoBenchmark.Reset;
  391. begin
  392. fLastUpdateTime := Now();
  393. fSpeed := 0;
  394. fCurrentProcess := 0;
  395. fFirstUpdateTime := 0;
  396. fEstimatedMilliseconds := 0;
  397. end;
  398. end.