gpt4 book ai didi

php - 测量类里面函数之间的时间?

转载 作者:行者123 更新时间:2023-11-29 20:34:01 25 4
gpt4 key购买 nike

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

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);
}

最佳答案

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

关于php - 测量类里面函数之间的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com