Home php教程 php手册 PHP 计算代码执行耗时的代码修正网上普遍错误

PHP 计算代码执行耗时的代码修正网上普遍错误

Jun 06, 2016 pm 08:36 PM
time consuming

前几天测试 SQLite 插入大数据量的时候, 找了一些关于计算执行时间的代码, 发现网上普遍流传着这样一份代码

代码如下:
$t1 = explode(' ', microtime());
// ... 执行代码 ...
$t2 = explode(' ', microtime());
echo ($t2[1]-$t1[1]).'s '.($t2[0]-$t1[0]).'ms';

其实稍微试一下, 就能发现这份代码有个严重的问题. 虽然 t2 得到的时间肯定比 t1 大, 但不代表, 它的微秒数就一定比 t1 的微秒数大. 所以直接相减的话, ms 部分有可能得到的是负数. 因此, 我自己稍微改动了一下, 代码如下:
代码如下:
$t1 = microtime(true);
// ... 执行代码 ...
$t2 = microtime(true);
echo '耗时'.round($t2-$t1,3).'秒';

简单说一下. microtime() 如果带个 true 参数, 返回的将是一个浮点类型. 这样 t1 和 t2 得到的就是两个浮点数, 相减之后得到之间的差. 由于浮点的位数很长, 或者说不确定, 所以再用个 round() 取出小数点后 3 位. 这样我们的目的就达到了~
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)