doujie3888 2017-02-01 04:07
浏览 64

PHP中的嵌套循环非常慢

I have 6 nested loops in a PHP program, however, the calculation time for the script is extremely slow. I would like to ask if there is a better way of implementing the 6 loops and increasing computation time, even if it means switching to another language. The nature of the algorithm I'm implementing requires iteration, so I don't know how I can better implement it.

Here's the code.

<?php
$time1 = microtime(true);
$res = 16;
$imageres = 128;
for($x=0;$x<$imageres;++$x){
    for($y=0;$y<$imageres;++$y){ 
        $pixels[$x][$y]=1;  
    }};
$quantizermatrix = 1;
$scalingcoefficient = 1/($res/2);
for($currentimagex=0;$currentimagex<($res*($imageres/$res-1)+1);$currentimagex = $currentimagex +$res){
    for($currentimagey=0;$currentimagey<($res*($imageres/$res-1)+1);$currentimagey = $currentimagey +$res){
        for($u=0;$u<$res;++$u){
            for($v=0;$v<$res;++$v){   
                for($x=0;$x<$res;++$x){
                    for($y=0;$y<$res;++$y){
                        if($u == 0) {$a = 1/(sqrt(2));} else{$a = 1;};
                        if($v == 0){$b = 1/(sqrt(2));}else{$b = 1;};
                        $xes[$y] = $pixels[$x+$currentimagex][$y+$currentimagey]*cos((M_PI/$res)*($x+0.5)*$u)*cos( M_PI/$res*($y+0.5)*$v);
                    }
                    $xes1[$x] = array_sum($xes);
                }
                $xes2= array_sum($xes1)*$scalingcoefficient*$a*$b;
                $dctarray[$u+$currentimagex][$v+$currentimagey] = round($xes2/$quantizermatrix)*$quantizermatrix;
            }}}};
foreach($dctarray as $dct){
    foreach($dct as $dc){
        echo $dc." ";
    }
    echo "<br>";}
$time2 = microtime(true);echo 'script execution time: ' . ($time2 - $time1);
?>

I've removed a large portion of the code that's irrelevant, since this is the section of the code that's problematic

Essentially the code iterates through every pixel in a PNG image and outputs a computed matrix (2d array). This code takes around 2 seconds for a 128x128 image. This makes this program impractical for normal images greater than 128x128

  • 写回答

1条回答 默认 最新

  • douhuan6065 2017-02-01 04:43
    关注

    There is a function available in Imagick library

    Imagick::exportImagePixels
    

    Refer the below link it might help you out http://www.php.net/manual/en/imagick.exportimagepixels.php

    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)