Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\system;
- class MicroTime {
- private $when = null;
- private $float = null;
- private $seconds = null;
- private $milliseconds = null;
- // Constructor for class
- public function __construct($when = null) {
- if (is_null($when)) {
- $when = microtime();
- }
- $this->when = $when;
- $this->setSecMSec($when);
- }
- public function elapsedTime()
- {
- return round((float) $this->seconds + $this->milliseconds / 1000.0, 3);
- }
- public function seconds()
- {
- return $this->seconds;
- }
- public function milliseconds()
- {
- return $this->milliseconds;
- }
- public function asfloat()
- {
- return $this->float;
- }
- public function when()
- {
- return $this->when;
- }
- public function asDateTime() {
- return \DateTime::createFromFormat('U,u', $this->seconds .','. $this->milliseconds * 1000);
- }
- // Format time to date and time
- public function asDateTimeStr() {
- $when = date_create_from_format('U', $this->seconds);
- return sprintf("%s.%03u", $when->format('Y-m-d H:i:s'), $this->milliseconds); ;
- }
- // always subtract the later from the earlier and change signs if required
- public function diff(MicroTime $then)
- {
- // which is earlier?
- $swapped = false;
- $mtL = $this;
- $mtE = $then;
- if ($mtL->float < $mtE->float) {
- $swapped = true;
- $mtE = $this;
- $mtL = $then;
- }
- $diff = new self();
- $diff->when = $mtL->when;
- $diff->float = $mtL->float - $mtE->float;
- $diff->seconds = (int) floor($diff->float);
- $diff->milliseconds = (int) round(($diff->float - $diff->seconds) * 1000.0, 0);
- if ($swapped) {
- $diff->float = $diff->float * -1.0;
- $diff->seconds = $diff->seconds * -1.0;
- $diff->milliseconds = $diff->milliseconds * -1.0;
- }
- return $diff;
- }
- /**
- *
- * @param type $when
- * @return array [seconds, milliseconds]
- */
- private function setSecMSec($when)
- {
- if (is_float($when)) {
- $this->float = $when;
- $this->seconds = (int) floor($when);
- $this->milliseconds = (int) round(($when - $this->seconds) * 1000.0, 0);
- }
- else {
- list($usec, $sec) = explode(' ', $when);
- $this->seconds = (int) $sec;
- $this->milliseconds = (int) round($usec * 1000.0, 0);
- $this->float = (float) $sec + (float) $usec;
- }
- }
- public function __get($name)
- {
- return $this->{$name};
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement