PHP Record code run time

Source: Internet
Author: User

Code Run Time Measurement

Typically in code that requires performance, the test code is added to the calculation.

But every time to write Microtime, End–start may not be too troublesome, so simply write a class to engage.

Code

Class timecost{Private $cost = Array ();    Private $record = Array ();    Private $scale = 6;        Public function __construct ($scale = 6) {$this->cost = array ();        $this->record = Array ();    $this->scale = $scale;    } public Function __tostring () {return $this->getstring ();     }/** * start to cal time.    * * @param mixed $key */Public Function Addcost ($key) {$this->cost[$key] = Microtime (true);     }/** * stop to Cal time. * * @param mixed $key */Public Function Closecost ($key) {$cost = Bcsub (Microtime (True), $this-        cost[$key], $this->scale); if (In_array ($key, Array_keys ($this->record))) {$this->record[$key] = Bcadd ($cost, $this->record[$key        ], $this->scale);        } else {$this->record[$key] = $cost;    } return $cost;         Public Function getString ($key = null) {if ($key) {   Return "{$key}[{$this->record[$key]}]";        } $str = ';        foreach ($this->record as $k = + $v) {$str. = "{$k}[{$v}]";    } return $STR; }}

Usage

$obj = new Timecost (); $token = ' test_a '; $obj->addcost ($token); Some_code (); $obj->closecost ($token); $reslut = $ Obj->getstring ($token);

Description

    • Time accuracy: The default is to retain 6 bits, is enough, want more precision, you can specify the $scale parameter when the new object

    • Token:token is meant to represent a piece of code, and the corresponding result is written to the record array in the form of key (token), value.

      So using a token multiple times for addcost and closeclost results will accumulate.

    • GetString: Passing tokens Returns the result of the token, and by default all results in the record are stitched back.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.