Quick.Chrono.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. { ***************************************************************************
  2. Copyright (c) 2015-2020 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 : 27/06/2020
  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. procedure Start;
  116. procedure Stop;
  117. procedure Reset;
  118. procedure Check;
  119. procedure BreakPoint;
  120. property IsHighResolution: Boolean read fIsHighResolution;
  121. property IsRunning: Boolean read GetIsRunning;
  122. property ReportFormatPrecission: TPrecissionFormat read fReportFormatPrecission write fReportFormatPrecission;
  123. property ElapsedTicks: Int64 read GetElapsedTicks;
  124. property ElapsedMilliseconds: Int64 read GetElapsedMilliseconds;
  125. property ElapsedMilliseconds_Breakpoint: Int64 read GetElapsedMilliseconds_BreakPoint;
  126. property ElapsedMillisecondsWithPrecission: Extended read GetElapsedMillisecondsWithPrecission;
  127. property ElapsedMillisecondsWithPrecission_BreakPoint: Extended read GetElapsedMillisecondsWithPrecission_BreakPoint;
  128. property ElapsedSeconds: Int64 read GetElapsedSeconds;
  129. function ElapsedTime(LongFormat : Boolean = False) : string;
  130. function ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  131. class function MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string; overload;
  132. class function MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string; overload;
  133. end;
  134. TChronoBenchmark = class
  135. private
  136. fTotalProcess : Int64;
  137. fLastUpdateTime : TDateTime;
  138. fCurrentProcess : Int64;
  139. fFirstUpdateTime : TDateTime;
  140. fEstimatedMilliseconds : Int64;
  141. fSpeed : Single;
  142. procedure SetCurrentProcess(NewCurrentProcess : Int64);
  143. function GetElapsedMilliseconds : Int64;
  144. public
  145. constructor Create;
  146. property TotalProcess : Int64 read fTotalProcess write fTotalProcess;
  147. property CurrentProcess : Int64 read fCurrentProcess write SetCurrentProcess;
  148. property Speed : Single read fSpeed write fSpeed;
  149. property ElapsedMilliseconds : Int64 read GetElapsedMilliseconds;
  150. property EstimatedMilliseconds : Int64 read fEstimatedMilliseconds write fEstimatedMilliseconds;
  151. function ElapsedTime(LongFormat : Boolean) : string;
  152. function EstimatedTime(LongFormat : Boolean) : string;
  153. procedure Reset;
  154. end;
  155. implementation
  156. { TChronometer Class }
  157. constructor TChronometer.Create(const StartOnCreate: Boolean = false);
  158. begin
  159. inherited Create;
  160. fIsRunning := False;
  161. fReportFormatPrecission := pfFloat;
  162. fStartCount := 0;
  163. fStopCount := 0;
  164. fStartBreakPoint := 0;
  165. fStopBreakPoint := 0;
  166. {$IF Defined(MSWINDOWS)}
  167. if not QueryPerformanceFrequency(fFrequency) then
  168. begin
  169. fIsHighResolution := False;
  170. //fFrequency := TTimeSpan.TicksPerSecond;
  171. fFrequency := MSecsPerSec;
  172. //TickFrequency := 1.0;
  173. end else
  174. begin
  175. fIsHighResolution := True;
  176. //TickFrequency := 10000000.0 / fFrequency;
  177. end;
  178. {$ELSEIF Defined(POSIX) OR Defined(LINUX)}
  179. fIsHighResolution := True;
  180. fFrequency := 10000000;
  181. //TickFrequency := 10000000.0 / fFrequency;
  182. {$ENDIF}
  183. if StartOnCreate then Start;
  184. end;
  185. function TChronometer.GetElapsedTicks: Int64;
  186. begin
  187. Result := fStopCount - fStartCount;
  188. end;
  189. function TChronometer.GetTickStamp : Int64;
  190. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  191. var
  192. res: timespec;
  193. {$ENDIF}
  194. begin
  195. {$IFDEF MSWINDOWS}
  196. if fIsHighResolution then QueryPerformanceCounter(Result)
  197. else Result := MilliSecondOf(Now);
  198. {$ELSE}
  199. {$IFDEF MACOS}
  200. Result := Int64(AbsoluteToNanoseconds(mach_absolute_time) div 100);
  201. {$ENDIF}
  202. {$IF (Defined(POSIX) OR Defined(LINUX)) AND NOT Defined(MACOS)}
  203. clock_gettime(CLOCK_MONOTONIC, @res);
  204. Result := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 100;
  205. {$ENDIF}
  206. {$ENDIF}
  207. end;
  208. function TChronometer.ElapsedTime(LongFormat : Boolean = False) : string;
  209. begin
  210. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission,fReportFormatPrecission,LongFormat);
  211. end;
  212. function TChronometer.ElapsedTime_BreakPoint(LongFormat : Boolean = False) : string;
  213. begin
  214. Result := MillisecondsToString(ElapsedMillisecondsWithPrecission_BreakPoint,fReportFormatPrecission,LongFormat);
  215. end;
  216. class function TChronometer.GetUnitTime(TimeValue : TTimeValue; LongFormat : Boolean) : string;
  217. begin
  218. if LongFormat then Result := ' ' + UnitLongTime[TimeValue] + '(s)'
  219. else Result := UnitShortTime[TimeValue];
  220. end;
  221. class function TChronometer.GetFmtTime(TimeFmt : TTimeFmt; LongFormat : Boolean) : string;
  222. begin
  223. if LongFormat then Result := FmtLongTime[TimeFmt]
  224. else Result := FmtShortTime[TimeFmt];
  225. end;
  226. function TChronometer.GetIsRunning: Boolean;
  227. begin
  228. Result := fIsRunning;
  229. end;
  230. class function TChronometer.MillisecondsToString(aMilliseconds : Int64; LongFormat : Boolean = False) : string;
  231. begin
  232. Result := MillisecondsToString(aMilliseconds.ToExtended,pfTruncate,LongFormat);
  233. end;
  234. class function TChronometer.Precission(aValue : Extended; FormatPrecission : TPrecissionFormat) : Extended;
  235. begin
  236. case FormatPrecission of
  237. pfRound : Result := Round(aValue).ToExtended;
  238. pfTruncate : Result := Int(aValue);
  239. else Result := aValue;
  240. end;
  241. end;
  242. class function TChronometer.MillisecondsToString(aMilliseconds : Extended; FormatPrecission : TPrecissionFormat = pfFloat; LongFormat : Boolean = False) : string;
  243. var
  244. dt : TDateTime;
  245. mc : Extended;
  246. begin
  247. if aMilliseconds < 1.0 then
  248. begin
  249. mc := frac(aMilliseconds) * 1000;
  250. if Int(mc) = 0 then Result := Format('%d%s',[Trunc(frac(mc) * 1000),GetUnitTime(utNanosecond,LongFormat)]) //nanoseconds
  251. else Result := Format('%d%s',[Trunc(mc),GetUnitTime(utMicrosecond,LongFormat)]); //microseconds
  252. end
  253. else
  254. begin
  255. if aMilliseconds < MSecsPerSec then //milliseconds
  256. begin
  257. aMilliseconds := Precission(aMilliseconds,FormatPrecission);
  258. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMillisecond,LongFormat)])
  259. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMillisecond,LongFormat)])
  260. end
  261. else if (aMilliseconds / MSecsPerSec) < SecsPerMin then //seconds
  262. begin
  263. aMilliseconds := Precission((aMilliseconds / MSecsPerSec),FormatPrecission);
  264. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utSecond,LongFormat)])
  265. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utSecond,LongFormat)]);
  266. end
  267. else if ((aMilliseconds / MSecsPerSec) < SecsPerHour) and ((Round(aMilliseconds) mod (SecsPerMin * MSecsPerSec)) = 0) then //minutes
  268. begin
  269. aMilliseconds := Precission((aMilliseconds / (SecsPerMin * MSecsPerSec)),FormatPrecission);
  270. if (FormatPrecission = pfFloat) or (frac(aMilliseconds) > 0) then Result := Format('%f%s',[aMilliseconds,GetUnitTime(utMinute,LongFormat)])
  271. else Result := Format('%d%s',[Trunc(aMilliseconds),GetUnitTime(utMinute,LongFormat)])
  272. end
  273. else if (aMilliseconds / MSecsPerSec) < SecsPerDay then //hours
  274. begin
  275. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  276. if LongFormat then
  277. begin
  278. if (aMilliseconds / MSecsPerSec) > SecsPerHour then Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))
  279. else Result := FormatDateTime(GetFmtTime(tfMinutesAndSeconds,LongFormat),Frac(dt));
  280. end
  281. else
  282. begin
  283. Result := FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt));
  284. end;
  285. end
  286. else //días
  287. begin
  288. dt := aMilliseconds / MSecsPerSec / SecsPerDay;
  289. Result := Format('%d%s, %s', [trunc(dt),GetUnitTime(utDay,LongFormat),FormatDateTime(GetFmtTime(tfHoursAndMinutes,LongFormat),Frac(dt))]);
  290. end;
  291. end;
  292. end;
  293. function TChronometer.GetElapsedMilliseconds : Int64;
  294. begin
  295. result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
  296. end;
  297. function TChronometer.GetElapsedMilliseconds_BreakPoint : Int64;
  298. begin
  299. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) div fFrequency;
  300. end;
  301. function TChronometer.GetElapsedMillisecondsWithPrecission : Extended;
  302. begin
  303. result := (MSecsPerSec * (fStopCount - fStartCount)) / fFrequency;
  304. end;
  305. function TChronometer.GetElapsedMillisecondsWithPrecission_BreakPoint : Extended;
  306. begin
  307. result := (MSecsPerSec * (fStopBreakPoint - fStartBreakPoint)) / fFrequency;
  308. end;
  309. function TChronometer.GetElapsedSeconds : Int64;
  310. begin
  311. result := ((MSecsPerSec * (fStopCount - fStartCount)) div fFrequency) div MSecsPerSec;
  312. end;
  313. procedure TChronometer.Start;
  314. begin
  315. fStartCount := GetTickStamp;
  316. fIsRunning := true;
  317. end;
  318. procedure TChronometer.Stop;
  319. begin
  320. fStopCount := GetTickStamp;
  321. fIsRunning := false;
  322. end;
  323. procedure TChronometer.Reset;
  324. begin
  325. fStartCount := GetTickStamp;
  326. end;
  327. procedure TChronometer.Check;
  328. begin
  329. if fIsRunning then fStopCount := GetTickStamp;
  330. end;
  331. procedure TChronometer.BreakPoint;
  332. begin
  333. if fIsRunning then
  334. begin
  335. if fStartBreakPoint = 0 then
  336. begin
  337. fStopBreakPoint := GetTickStamp;
  338. fStartBreakPoint := fStartCount;
  339. end
  340. else
  341. begin
  342. fStartBreakPoint := fStopBreakPoint;
  343. fStopBreakPoint := GetTickStamp;
  344. end;
  345. end
  346. else fStopBreakPoint := fStopCount;
  347. end;
  348. { TChronoBenchmark Class }
  349. constructor TChronoBenchmark.Create;
  350. begin
  351. inherited;
  352. fTotalProcess := 0;
  353. fSpeed := 0;
  354. fLastUpdateTime := Now();
  355. fCurrentProcess := 0;
  356. fFirstUpdateTime := 0;
  357. fEstimatedMilliseconds := 0;
  358. end;
  359. procedure TChronoBenchmark.SetCurrentProcess(NewCurrentProcess : Int64);
  360. begin
  361. //corrects first time run
  362. if fLastUpdateTime = 0 then fLastUpdateTime := Now();
  363. if fFirstUpdateTime = 0 then fFirstUpdateTime := Now();
  364. //calculates operation speed
  365. fSpeed := (NewCurrentProcess - fCurrentProcess) / ((Now() - fLastUpdateTime) * 86400);
  366. if fSpeed = 0 then fSpeed := 0.1;
  367. //returns estimated time string
  368. fEstimatedMilliseconds := Round(((TotalProcess - NewCurrentProcess) / fSpeed) * 1000);
  369. //save current values
  370. fLastUpdateTime := Now();
  371. fCurrentProcess := NewCurrentProcess;
  372. end;
  373. function TChronoBenchmark.GetElapsedMilliseconds : Int64;
  374. begin
  375. Result := Round(((Now() - fFirstUpdateTime) * 86400 * 1000));
  376. end;
  377. function TChronoBenchmark.ElapsedTime(LongFormat : Boolean) : string;
  378. begin
  379. Result := TChronometer.MillisecondsToString(GetElapsedMilliseconds,LongFormat);
  380. end;
  381. function TChronoBenchmark.EstimatedTime(LongFormat : Boolean) : string;
  382. begin
  383. Result := TChronometer.MillisecondsToString(fEstimatedMilliseconds,LongFormat);
  384. end;
  385. procedure TChronoBenchmark.Reset;
  386. begin
  387. fLastUpdateTime := Now();
  388. fSpeed := 0;
  389. fCurrentProcess := 0;
  390. fFirstUpdateTime := 0;
  391. fEstimatedMilliseconds := 0;
  392. end;
  393. end.