1<?php
2/*
3 * This file is part of the PHP_Timer package.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11/**
12 * Utility class for timing.
13 */
14class PHP_Timer
15{
16    /**
17     * @var array
18     */
19    private static $times = array(
20      'hour'   => 3600000,
21      'minute' => 60000,
22      'second' => 1000
23    );
24
25    /**
26     * @var array
27     */
28    private static $startTimes = array();
29
30    /**
31     * @var float
32     */
33    public static $requestTime;
34
35    /**
36     * Starts the timer.
37     */
38    public static function start()
39    {
40        array_push(self::$startTimes, microtime(true));
41    }
42
43    /**
44     * Stops the timer and returns the elapsed time.
45     *
46     * @return float
47     */
48    public static function stop()
49    {
50        return microtime(true) - array_pop(self::$startTimes);
51    }
52
53    /**
54     * Formats the elapsed time as a string.
55     *
56     * @param  float  $time
57     * @return string
58     */
59    public static function secondsToTimeString($time)
60    {
61        $ms = round($time * 1000);
62
63        foreach (self::$times as $unit => $value) {
64            if ($ms >= $value) {
65                $time = floor($ms / $value * 100.0) / 100.0;
66
67                return $time . ' ' . ($time == 1 ? $unit : $unit . 's');
68            }
69        }
70
71        return $ms . ' ms';
72    }
73
74    /**
75     * Formats the elapsed time since the start of the request as a string.
76     *
77     * @return string
78     */
79    public static function timeSinceStartOfRequest()
80    {
81        return self::secondsToTimeString(microtime(true) - self::$requestTime);
82    }
83
84    /**
85     * Returns the resources (time, memory) of the request as a string.
86     *
87     * @return string
88     */
89    public static function resourceUsage()
90    {
91        return sprintf(
92            'Time: %s, Memory: %4.2fMB',
93            self::timeSinceStartOfRequest(),
94            memory_get_peak_usage(true) / 1048576
95        );
96    }
97}
98
99if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
100    PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
101} elseif (isset($_SERVER['REQUEST_TIME'])) {
102    PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME'];
103} else {
104    PHP_Timer::$requestTime = microtime(true);
105}
106