我不认为这是重复的,我一直在寻找它,但确实不知道确切地称呼什么。

我想知道为什么循环比另一个循环大十倍并不需要十倍的时间才能运行。

我正在做一些测试,试图弄清楚如何使我的网站更快,更活跃,因此我在功能前后使用了microtime()。在我的网站上,我不确定如何在不遍历整个表的情况下提取具有某些属性的表行列表,并且我想知道这是否使我减速。

因此,使用以下循环:

echo microtime(), "<br>";
echo microtime(), "<br>";
session_start();
$connection = mysqli_connect("localhost", "root", "", "") or die(mysqli_connection_error());;
echo microtime(), "<br>";
echo microtime(), "<br>";
$x=1000;
$messagequery = mysqli_query($connection, "SELECT * FROM users WHERE ID='$x'");
while(!$messagequery or mysqli_num_rows($messagequery) == 0) {
    echo('a');
    $x--;
    $messagequery = mysqli_query($connection, "SELECT * FROM users WHERE ID='$x'");
    }
echo "<br>";
echo microtime(), "<br>";
echo microtime(), "<br>";


我得到以下输出和类似的输出:

0.14463300 1376367329
0.14464400 1376367329
0.15548900 1376367330
0.15550000 1376367330 < these two
[a's omitted, for readability]
0.33229800 1376367330 < these two
0.33230700 1376367330


〜18-20微秒,还不错,没有人会注意到。所以我想知道随着我的网站的发展会发生什么。如果我要搜索的表行数是(10,000)的10倍,该怎么办?

0.11086600 1376367692
0.11087600 1376367692
0.11582100 1376367693
0.11583600 1376367693
[lots of a's]
0.96294500 1376367694
0.96295500 1376367694


〜83-88微秒。为什么不是180-200微秒?启动和停止循环是否需要时间?

更新:要查看是否是mySQL添加变量,我在没有mySQL的情况下对其进行了测试:

echo microtime(), "<br>";
echo microtime(), "<br>";
session_start();
$connection = mysqli_connect("localhost", "root", "W2072a", "triiline1") or die(mysqli_connection_error());;
echo microtime(), "<br>";
echo microtime(), "<br>";
$x=1000000;
while($x > 10) {
    echo('a');
    $x--;
    }
echo "<br>";
echo microtime(), "<br>";
echo microtime(), "<br>";


现在看来,一百万个需要约100毫秒(对吗?),一千万个需要约480毫秒。因此,我的问题仍然存在。为什么较大的循环运动更快?这并不重要,我并没有基于此计划整个网站的设计,但是我对此很感兴趣。

最佳答案

通常,循环将线性缩放。

可能的错误:如果您尚未这样做,请考虑如果没有ID为900的记录,可能会发生什么。

我强烈建议使用MySQL通过WHERE子句为您完成过滤工作,而不是通过这种方式对信息进行排序。它不是真正可扩展的。

坦白说


  while(!$ messagequery或mysqli_num_rows($ messagequery)== 0){


对我来说没有意义。如果发生故障,$messagequery将为false,我想只要mysqli_num_rows($messagequery)不等于零,就希望循环运行。但是,这不是上面的代码所做的。

如果mysqli_num_rows($messagequery)等于零,则循环将继续。

如果mysqli_num_rows($messagequery)不等于零,则循环将停止。

请参阅运算符优先级:http://php.net/manual/en/language.operators.precedence.php

这是否有助于回答您的问题?

关于php - 为什么循环不均匀缩放?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18200651/

10-11 02:45
查看更多