Search the Community
Showing results for tags 'php memory leak arrays'.
-
My PHP script is running out of memory. I have put memory_get_usage( ) inside the loops and found that it is running out of memory after 6MB. I would like to clearly explain my script and like to get suggestions from you. I am not sure, If my script is running out of memory because of problems with code . So, here is the algorithm for my script: Read the input json data into an array ( approximatley 200 lines of data) calculate the sum of the array ($sum) 3 variables $starting, $ending and $compare.( Intialize $compare = $starting) start with $starting=$vmin , calculate scaling factor, scale the original array and calculate sum of it .That new sum is $ending. Add 10 to $starting until the diff between $ending and $compare is 50. repeat all the steps until $vmin reaches $vmax with an increment of $vinc The above algorithm might look insane, But it finds an optimal solution for supply chain related optimization problem. I would like you to see if my weak coding capabilities are the reason for the memory outage .If so, Please suggest the changes to my script. Here is my code <code> $vmax = 10000; $vmin = 1000; $vinc = 2000; //decode the json data $fp = fopen("data_save3.json", "r"); $inp=file_get_contents("data_save3.json"); fclose($fp); $inp=json_decode($inp); //calculate the array sum foreach($inp as $i=>$element) { foreach($element as $j=>$sub_element) { $sum+= $inp[$i][$j]; } } //start at vmin and increment it until vmax for(;$vmin <=$vmax ; ) { $starting=$vmin; $compare = $starting; //calculate scaling factor $scale = $starting/$sum; //calculate the scaled array $sum2 = 0; $inp_info2 = $inp; $ending = newscale($inp_info2,$scale,$sum2); $optimal = getClosest($starting,$ending,$compare,$sum); echo $optimal.PHP_EOL; $vmin = $vmin+$vinc ; } // function to find the closest value $inp_info1=$inp; function getClosest($starting,$compare,$ending,$sum,$inp) { global $sum2; global $compare; global $inp_info1; global $starting , $ending, $scale1, $sum, $inp, $inp_info2, $inp_info3,$rowsum2, $rowsum3, $rowsum4, $rowsum5; if (abs($ending - $compare) < 50){ return $starting; } else{ $starting = $starting +10; $scale1 = $starting/$sum; $inp_info1 = $inp; $sum2 = 0; $ending = newscale($inp_info1,$scale1,$sum2); return getClosest($starting); } } //array scaling function function newscale($array,$scale,$sum2){ global $sum2,$scale; foreach($array as $i=>$element) { foreach($element as $j=>$sub_element) { $array[$i][$j]*= $scale; $array[$i][$j] = truncate($array[$i][$j]); $sum2+=$array[$i][$j]; } } return $sum2; } //truncate function function truncate($num, $digits = 0) { $shift = pow(10, $digits); return ((floor($num * $shift)) / $shift); } </code>