【发布时间】:2015-08-12 23:03:00
【问题描述】:
所以我想弄清楚为什么这段 PHP 代码运行时间太长才能输出结果。
例如,这是我的apitest.php,这是我的 PHP 代码
<?php
function getRankedMatchHistory($summonerId,$serverName,$apiKey){
$k
$d;
$a;
$timeElapsed;
$gameType;
$championName;
$result;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$serverName.".api.pvp.net/api/lol/".$serverName."/v2.2/matchhistory/".$summonerId."?api_key=".$apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$matchHistory = json_decode($response,true); // Is the Whole JSON Response saved at $matchHistory Now locally as a variable or is it requested everytime $matchHistory is invoked ?
for ($i = 9; $i >= 0; $i--){
$farm1 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["minionsKilled"];
$farm2 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralMinionsKilled"];
$farm3 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralminionsKilledTeamJungle"];
$farm4 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralminionsKilledEnemyJungle"];
$elapsedTime = $matchHistory["matches"][$i]["matchDuration"];
settype($elapsedTime, "integer");
$elapsedTime = floor($elapsedTime / 60);
$k = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["kills"];
$d = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["deaths"];
$a = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["assists"];
$championIdTmp = $matchHistory["matches"][$i]["participants"]["0"]["championId"];
$championName = call_user_func('getChampionName', $championIdTmp); // calls another function to resolve championId into championName
$gameType = preg_replace('/[^A-Za-z0-9\-]/', ' ', $matchHistory["matches"][$i]["queueType"]);
$result = (($matchHistory["matches"][$i]["participants"]["0"]["stats"]["winner"]) == "true") ? "Victory" : "Defeat";
echo "<tr>"."<td>".$gameType."</td>"."<td>".$result."</td>"."<td>".$championName."</td>"."<td>".$k."/".$d."/".$a."</td>"."<td>".($farm1+$farm2+$farm3+$farm4)." in ". $elapsedTime. " minutes". "</td>"."</tr>";
}
}
?>
我想知道的是如何让页面输出更快 10~15 秒输出结果,使浏览器认为网站已死,就像 500 内部错误或类似的东西。
这里是一个简单的演示,它可能需要多长时间:Here
您可能已经注意到,是的,我正在使用 Riot API,它以 JSON 编码类型发送响应。
这是此函数处理的响应示例:Here
我想到的是在 CURL 函数的开头创建一个名为 temp.php 的临时文件,并将整个响应保存在那里,然后从那里读取变量,这样我就可以加快进程并在读取变量后删除它创建的temp.php 从而释放了磁盘空间。并提高速度。
但我不知道如何在 PHP 中做到这一点。
顺便说一句,我今天才开始使用 PHP,所以如果可能的话,我希望能对答案进行一些解释。
感谢您宝贵的时间。
【问题讨论】:
-
JSON 响应存储在本地
$matchHistory中,因此无需将其写入文件。 -
那为什么加载页面需要很长时间,看看演示链接。
-
尝试直接在浏览器中访问 API URL,看看需要多长时间。有可能他们的服务器给你响应的速度很慢。
-
您需要使用
microtime(true)进行基准测试 -
local file on remote filesystem听起来很矛盾...
标签: php curl firewall resolver