【问题标题】:Measure time between functions in class?在课堂上测量功能之间的时间?
【发布时间】:2016-08-11 08:29:10
【问题描述】:

我正在尝试了解 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);
 }

【问题讨论】:

  • elapsedTime 定义在哪里?
  • 为清晰起见已更新

标签: php mysql class oop


【解决方案1】:

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

【讨论】:

  • 我明白你的意思!我添加了elapsedTime 函数。这不应该是一个重点,不是吗?
  • 该函数仍将返回“now - then”,“then”是构造函数初始化的时间,因此当这些任务完成时,您实际上是在查看时钟,但如果分针是仍然在 1 上,即使您看了 3 次也不意味着已经过了 3 分钟;)。然而,这在逻辑上是有道理的,因为与实际提交查询并获得结果相比,连接、选择、获取版本这三个操作实际上都是即时的。
  • 非常类似于时钟。我现在完全明白这个问题了!谢谢
猜你喜欢
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多