1 <?php
2 /**
3 * @package FrameworkOnFramework
4 * @subpackage utils
5 * @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
6 * @license GNU General Public License version 2 or later; see LICENSE.txt
7 */
8
9 defined('FOF_INCLUDED') or die;
10
11 /**
12 * An execution timer monitor class
13 */
14 class FOFUtilsTimer
15 {
16 /** @var float Maximum execution time allowance */
17 private $max_exec_time = null;
18
19 /** @var float Timestamp of execution start */
20 private $start_time = null;
21
22 /**
23 * Public constructor, creates the timer object and calculates the execution
24 * time limits.
25 *
26 * @param float $max_exec_time Maximum execution time allowance
27 * @param float $runtime_bias Execution time bias (expressed as % of $max_exec_time)
28 */
29 public function __construct($max_exec_time = 5.0, $runtime_bias = 75.0)
30 {
31 // Initialize start time
32 $this->start_time = $this->microtime_float();
33
34 $this->max_exec_time = $max_exec_time * $runtime_bias / 100.0;
35 }
36
37 /**
38 * Wake-up function to reset internal timer when we get unserialized
39 */
40 public function __wakeup()
41 {
42 // Re-initialize start time on wake-up
43 $this->start_time = $this->microtime_float();
44 }
45
46 /**
47 * Gets the number of seconds left, before we hit the "must break" threshold. Negative
48 * values mean that we have already crossed that threshold.
49 *
50 * @return float
51 */
52 public function getTimeLeft()
53 {
54 return $this->max_exec_time - $this->getRunningTime();
55 }
56
57 /**
58 * Gets the time elapsed since object creation/unserialization, effectively
59 * how long we are running
60 *
61 * @return float
62 */
63 public function getRunningTime()
64 {
65 return $this->microtime_float() - $this->start_time;
66 }
67
68 /**
69 * Returns the current timestamp in decimal seconds
70 *
71 * @return float
72 */
73 private function microtime_float()
74 {
75 list($usec, $sec) = explode(" ", microtime());
76 return ((float)$usec + (float)$sec);
77 }
78
79 /**
80 * Reset the timer
81 */
82 public function resetTime()
83 {
84 $this->start_time = $this->microtime_float();
85 }
86
87 }