【发布时间】:2018-08-30 10:02:00
【问题描述】:
我有这个函数,它使用折旧表中的数据计算固定资产的“账面价值”,Ii 在本地主机上运行良好,但是当我尝试继续生产时,在花费很长时间后出现“请求超时”加载,我想我搞砸了循环或其他东西,如果有人建议代码优化或破解以使这个功能更快,那就太好了。
我尝试限制要循环的记录数,它奏效了,但不幸的是,我有超过 20,000 个数据要处理。
$cat = null;
$total_a = null;
$assets = $this->Depreciation->get_all();
if (!empty($assets)) {
foreach ($assets as $asset) {
$cost = $asset->cost + $asset->add_cost + $asset->adj_cost;
$salve = $asset->salvage_value;
$life = $asset->life;
$life_t = 0;
$counter = 0;
$date1 = date('Y-12-31');
$date2 = $asset->in_service;
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365 * 60 * 60 * 24));
$months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
$in_service_d = date('Y-12-31');
if ($asset->rev > 0) {
$cost = $asset->rev;
}
$dep1 = ($cost - $salve) / $life * ($months / 12);
$dep = ($cost - $salve) / $life;
$total = 0;
$year = 1;
for (; $cost > $salve;) {
if ($year == 1 && $months < 12) {
$life_t++;
$year++;
$cost = $cost - $dep1;
$counter++;
$total = $dep1 + $total;
if($in_service_d == date('Y-12-31')){
$total_a = $total_a + $cost;
}
$in_service_d = date('Y-12-31', strtotime("+12 months", strtotime($in_service_d)));
} elseif ($year != 1) {
$life_t++;
if ($life_t > $life) {
$dep = $dep - $dep1;
}
$cost = $cost - $dep;
$counter++;
$total = $dep + $total;
if($in_service_d == date('Y-12-31')){
$total_a = $total_a + $cost;
}
$in_service_d = date('Y-12-31', strtotime("+12 months", strtotime($in_service_d)));
}
}
}
}
return $total_a;
【问题讨论】:
-
如果不涉及数据库操作,20000行并不是特别庞大的数据集。我还没有完成整个程序逻辑,但只要
$cost大于$salve,你就会循环运行。您确定$cost正在下降,还是$salve在迭代中上升? -
一个建议:您的程序逻辑太复杂,无法测试。我建议你将你的逻辑分解成更小的函数,并对它们中的每一个进行测试。这样您就可以更加确定每个部分在做什么。
-
成本正在下降
$cost = $cost - $dep1;或$cost = $cost - $dep;取决于每次迭代的`$Year` -
我怀疑问题出在循环上,但我无法弄清楚这个循环为什么只需要 21 条记录就需要这么长时间。
-
我们可以提供一些
$asset的示例数据吗?很难理解你的程序逻辑。
标签: php codeigniter request timeout