PHP exec() 和运行 shell 脚本给出不同的结果

标签 php bash shell

我有 script.sh,它向某个 URL 发送请求并使用 whet 打印执行时间。这是源代码:

time wget http://some.url

当我从命令行运行它时,我看到的时间结果精确到小数点后 3 位:

real    0m0.584s
user    0m0.000s
sys     0m0.002s

但是,当我使用 PHP 函数 exec("script.sh", $output) - 运行此 SH 时,我看到的时间结果精度仅为小数点后两位:

0.00user 0.00system 0:00.32elapsed 0%CPU (0avgtext+0avgdata 3788maxresident)k

如何获得与在命令行中看到的相同结果?

最佳答案

答案是in the manual :

Note: some shells (e.g., bash(1)) have a built-in time command that provides less functionality than the command described here. To access the real command, you may need to specify its pathname (something like /usr/bin/time).

您将从内置的 bash 中获得更高的精度;如果您从 shell 运行 /usr/bin/time 您也会看到两位小数。

不幸的是,time 是一个特殊情况,因为它是一个关键字,实际上并不是一个内置命令。否则,可以使用 bash 的内置命令来强制它。

所以看起来你只能保留两位小数,除非你想尝试不同的方法:

start_time=`date +%s%N`
wget http://some.url
end_time=`date +%s%N`
bc -l <<< "scale=4;($end_time - $start_time) / 1000000000"

关于PHP exec() 和运行 shell 脚本给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951843/

相关文章:

php - 使用 jquery 的一页 Codeigniter 站点? Ajax ?

PHPUnit:模拟函数

php - MYSQL Between 子句

linux - 使用 shell 解析字符串

java - Bash 去除传递给 java 命令行应用程序的引号

Web 服务器上的 PHP Websocket

linux - 为什么这个用于匹配数字的 sed 命令不起作用?

linux - alertlofile的一周信息

linux - shell 脚本中的 Munin

mysql - 在终端中定义 mysql 的分隔符