PHP Microtime Class

P

Microtime is a useful function that “returns the current Unix timestamp with microseconds.” [1] So as in normal this can be useful for time tracking, but also needs some arrangements.

I figured out this as a simple class. Example:

[code lang=”php”] //get instance
$time = new time();

//start with died parameter (default false)
$time->start($died = true);

//do nothing for 1 second (1000 miliseconds)
usleep(1000);

//stop the tracker
$time->end();
[/code]

It’s gonna echo “1 second”. And here is class:

[code lang=”php”]

class time {

private $start_time;
private $end_time;
private $difference;
private $died;
private $output;

public function __construct($died = false, $output = true) {
$this -> died = $died;
$this -> output = $output;
}

public function start() {
$this -> start_time = $this -> getTime();
}

public function end() {
$this -> end_time = $this -> getTime();
if ($this -> output)
$this -> printOut();
}

public function printOut() {
$this -> difference = $this -> end_time – $this -> start_time;
echo $this -> difference." seconds";
if($this -> died) die($this -> difference);
}

public function getTime() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
[/code]

I hope you enjoy this.

[1]: http://php.net/manual/en/function.microtime.php
[2]: getTime() function is excerpted from manual.

Yorum yaz

Oğulcan

Arşivler

Kategoriler