测量课堂上的功能之间的时间?

时间:2016-08-11 08:29:11

标签: php mysql class oop

我正在尝试理解OOP并创建自己的类来对MySQL数据库进行基准测试

class Benchmark
{

    protected $sql, $db;
    public $result, $time;

    public function __construct($host, $user, $pass, $db, $result = array(), $time = null)
    {

        /* Vars */
        $this->db = $db;
        $this->result = $result;
        $this->time = $time;

        /*Start Timer */
        $this->time = microtime(true);

        /* Connect to DB */
        $this->sql = new \mysqli($host, $user, $pass);

        /* Measure Time and put result to array */
        $this->result['benchmark']['connect'] = $this->elapsedTime($this->time);


    }

    public function testMySQL()
    {

        /* Connect to DB */
        $this->sql->select_db($this->db);
        $this->result['benchmark']['selectDb'] = $this->elapsedTime($this->time);

        /* Fetch Version */
        $version = $this->sql->server_version;
        $this->result['benchmark']['version'] = $this->elapsedTime($this->time);
        $this->result['info']['version'] = $version;

        /* Benchmark */
        $this->sql->query('SELECT BENCHMARK(1000000,ENCODE("hello",RAND()));');
        $this->result['benchmark']['result'] = $this->elapsedTime($this->time);

        /* Close Connection */
        $this->sql->close();

        /* Total Time */
        $this->result['info']['total'] = $this->elapsedTime($this->time);

        $this->dump($this->result);

    }
}

然而,结果如下:

Array
(
[benchmark] => Array
    (
        [connect] => 0.001
        [selectDb] => 0.001
        [version] => 0.001
        [result] => 10.181
    )

[info] => Array
    (
        [version] => 50713
        [total] => 10.181
    )

)

为什么时间不加起来?在这种情况下,[total]不应该是10.184吗?

最初的想法是从这里开始的:https://github.com/odan/benchmark-php并且有效。如果我在该脚本上使用相同的数据,它会加起来,我错在哪里?我想这与我缺乏OOP有关...

修改

 public function elapsedTime($time)
 {
     return number_format(microtime(true) - $time, 3);
 }

1 个答案:

答案 0 :(得分:0)

如果您正在测量自计时器启动以来经过的时间,那么每个输出只是该时间段内的一个点。从初始化计时器到获得结果所花费的时间除了连接,选择数据库和获取版本所需的时间,这些只是沿途的检查点(似乎几乎同时发生,至少在此计时器的分辨率下)。因此,执行前三个操作所花费的总时间 10.181.001,而不是.003