我的代码是否使用最佳方式读取 php 中的标准输入?
我正在使用 PHP CLI 来提供标准输入。我是否使用了读取该输入的最佳方法?
比如我会给它提供50000行数据。每行包含两个数字。我下面的代码是读取 50,000 行数据的最有效方法吗?或者这是一种非常低效的方法?
这是我的代码:
<?php
// Testing time period for execution
// Time tracker: TESTING
$micropoint1 = microtime(true);
// First, retrieve the number of points that will be provided.
$no_points = fgets(STDIN);
for($i=1, $max=$no_points+1; $i<$max; $i++) {
list($x, $y) = fscanf(STDIN, "%d %d"); // Get the string returned from the command line and convert to an array
}
// Time tracker: TESTING
$micropoint2 = microtime(true);
$pointelapsed = $micropoint2 - $micropoint1;
fwrite(STDOUT, "\nPoint Loop Took ".$pointelapsed." microsecs\n");
?>
I am using PHP CLI to provide standard input. Am I using the optimal method of reading that input?
For example, I will provide it 50,000 lines of data. Each line contains two numbers. Is my code below the most efficient way to read 50,000 lines of data? Or this a very inefficient way to do so?
Here is my code:
<?php
// Testing time period for execution
// Time tracker: TESTING
$micropoint1 = microtime(true);
// First, retrieve the number of points that will be provided.
$no_points = fgets(STDIN);
for($i=1, $max=$no_points+1; $i<$max; $i++) {
list($x, $y) = fscanf(STDIN, "%d %d"); // Get the string returned from the command line and convert to an array
}
// Time tracker: TESTING
$micropoint2 = microtime(true);
$pointelapsed = $micropoint2 - $micropoint1;
fwrite(STDOUT, "\nPoint Loop Took ".$pointelapsed." microsecs\n");
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我无法想象你的方法会变得更加有效。
I can't imagine your approach getting any more efficient.
为了提高效率,最好:
To be more efficient, it's better to:
因为它显然非常小,不能进一步削弱。但是,由于您没有指定,因此您只想优化循环。然后我对其余代码进行了几点说明。
显示微时间时,您可以执行以下操作:
此外,如果
fscanf()
无法返回任何内容,会发生什么情况。不会报错吗..As it is clearly very minimal and cannot be nerfed any further. However, since you didn't specify, that you want to optimize the loop only. Then I few points for the rest of the code.
When displaying the microtime, you can do this:
And also, what happens if
fscanf()
cant return anything. Wouldn't it give out an error..?