Quick.Chrono.pas 14 KB

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