PHP头条
热点:

要知道脚本消耗多少 CPU 功率,我们需要看看 ‘user time’ 和 ’system time’ 两个参数的值。秒和微秒部分默认是单独提供的。你可以除以 100 万微秒,并加上秒的参数值,得到一个十进制的总秒数。让我们来看一个例子:

以下为引用的内容:

// sleep for 3 seconds (non-busy)
sleep(3);

$data = getrusage();
echo "User time: ".
 ($data['ru_utime.tv_sec'] +
 $data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
 ($data['ru_stime.tv_sec'] +
 $data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 0.011552
System time: 0
*/

尽管脚本运行用了大约 3 秒钟,CPU 使用率却非常非常低。因为在睡眠运行的过程中,该脚本实际上不消耗 CPU 资源。还有许多其他的任务,可能需要一段时间,但不占用类似等待磁盘操作等 CPU 时间。因此正如你所看到的,CPU 使用率和运行时间的实际长度并不总是相同的。下面是一个例子:

以下为引用的内容:

// loop 10 million times (busy)
for($i=0;$i<10000000;$i++) {

}

$data = getrusage();
echo "User time: ".
 ($data['ru_utime.tv_sec'] +
 $data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
 ($data['ru_stime.tv_sec'] +
 $data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 1.424592
System time: 0.004204
*/

这花了大约 1.4 秒的 CPU 时间,但几乎都是用户时间,因为没有系统调用。系统时间是指花费在执行程序的系统调用时的 CPU 开销。下面是一个例子:

以下为引用的内容:

$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) - $start < 3) {

}

$data = getrusage();
echo "User time: ".
 ($data['ru_utime.tv_sec'] +
 $data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
 ($data['ru_stime.tv_sec'] +
 $data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 1.088171
System time: 1.675315
*/

现在我们有相当多的系统时间占用。这是因为脚本多次调用 microtime() 函数,该函数需要向操作系统发出请求,以获取所需时间。你也可能会注意到运行时间加起来不到 3 秒。这是因为有可能在服务器上同时存在其他进程,并且脚本没有 100% 使用 CPU 的整个 3 秒持续时间。

5、魔术常量

PHP 提供了获取当前行号 (__LINE__)、文件路径 (__FILE__)、目录路径 (__DIR__)、函数名 (__FUNCTION__)、类名 (__CLASS__)、方法名 (__METHOD__) 和命名空间 (__NAMESPACE__) 等有用的魔术常量。在这篇文章中不作一一介绍,但是我将告诉你一些用例。当包含其他脚本文件时,使用 __FILE__ 常量(或者使用 PHP5.3 新具有的 __DIR__ 常量):

以下为引用的内容:

// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
require_once('config/database.php');

// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . '/config/database.php');

使用 __LINE__ 使得调试更为轻松。你可以跟踪到具体行号。

以下为引用的内容:

// some code
// ...
my_debug("some debug message", __LINE__);
/* prints
Line 4: some debug message
*/

// some more code
// ...
my_debug("another debug message", __LINE__);
/* prints
Line 11: another debug message
*/

function my_debug($msg, $line) {
 echo "Line $line: $msg

6、生成唯一标识符

某些场景下,可能需要生成一个唯一的字符串。我看到很多人使用 md5() 函数,即使它并不完全意味着这个目的:

以下为引用的内容:

// generate unique string
echo md5(time() . mt_rand(1,1000000));
There is actually a PHP function named uniqid() that is meant to be used for this.

// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/

// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/

www.phpzy.comtrue/php/711.htmlTechArticle要知道脚本消耗多少 CPU 功率,我们需要看看 user time 和 system time 两个参数的值。秒和微秒部分默认是单独提供的。你可以除以 100 万微秒,并加上秒的参...

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐