Although I am a newbie in PHP, I saw a piece of code today and couldn't help but modify a few lines.
-
-
class runTime { - var $StartTime = 0;
- var $StopTime = 0;
- var $TimeSpent = 0;
function start(){
- $this->StartTime = microtime();
- }
function stop(){
- $this->StopTime = microtime();
- }< /p>
function spent() {
- if ($this->TimeSpent) {
- return $this->TimeSpent;
- } else {
- $StartMicro = substr($this->StartTime, 0,10);
- $StartSecond = substr($this->StartTime,11,10);
- $StopMicro = substr($this->StopTime,0,10);
- $StopSecond = substr($this- >StopTime,11,10);
- $start = floatval($StartMicro) + $StartSecond;
- $stop = floatval($StopMicro) + $StopSecond;
- $this->TimeSpent = $stop - $start;
- return round($this->TimeSpent,8);
- }
- } // end function
- }
-
Copy code
1. Why is it said that the packaging is improper?
During the use, I found that there is no need for the attributes of those classes to appear in the form of var (public). Since class is used, then follow some basic rules for objects below. These variables can be controlled using private access. .
2. Microtime is not used well enough?
Some instructions about microtime in the manual:
Definition and Usage
The microtime() function returns the current Unix timestamp and microseconds.
If called without optional parameters, this function returns a string in the format of "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), msec It's the microsecond part. Both parts of the string are returned in seconds.
In PHP5 and above, the parameter true can be accepted, so that floating point numbers can be returned directly, and the efficiency will be much higher than now.
The following is a small code found online for reference:
-
-
- function microtime_float3(){
- return microtime(true);
- }
function microtime_float2(){
- if( PHP_VERSION > ; 5){
- return microtime(true);
- }else{
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$usec + (float)$sec) ;
- }
- }
function microtime_float(){
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$usec + ( float)$sec);
- }
function runtime($t1){
- return number_format((microtime_float() - $t1)*1000, 4).'ms';
- }< ;/p>
$t1 = microtime_float();
- for($i=0;$i<10000;$i++){
- microtime_float();
- }
- echo "microtime_float=====" ;
- echo runtime($t1).'
';
- $t1 = microtime(true);
for($i=0;$i<10000;$i++) { - microtime(true);
- }
- echo "microtime_true=====";
- echo runtime($t1).'
';
- $t1 = microtime(true);
-
for($i=0;$i<10000;$i++){
- microtime_float2();
- }
echo "microtime_float2=====";
- echo runtime ($t1).'
';
- $t1 = microtime(true);
for($i=0;$i<10000;$i++){
- microtime_float3(
- winxp running results:
microtime_float=====109.5631ms
microtime_true=====38.8160ms
microtime_float2=====52.7902ms
microtime_float3=====45.0699ms
Running results on Linux:
microtime_float=====47.2510ms
microtime_true=====9.2051ms
microtime_float2=====16.3319ms
microtime_float3======12.2800ms
-
-
-
-
|