2010-08-15 3 views
7

Используя приведенный ниже код каждой загрузки изображения) file_get_contents()) в среднем занимает 8-15 секунд .....file_get_contents() с контекстом, чтобы использовать HTTP/1.1 значительно медленно скорость загрузки

Если я не использую контекст на file_get_contents(), тогда загрузка изображения меньше секунды.

Если я изменю $ opts, ниже, я получаю такую ​​же производительность, как и file_get_contents(), без контекста, который занимает 13 секунд для обработки 2,500 изображений.

$opts = array(
    'http'=>array(
     'protocol_version'=>'1.1', 
     'method'=>'GET', 
     'header'=>array(
      'Connection: close' 
     ), 
     'user_agent'=>'Image Resizer' 
    ) 
); 

ВОПРОИЗВЕДЕНИЕ:

$start_time = mktime(); 
$products = array(
     array('code'=>'A123', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A124', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A125', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A126', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A127', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A128', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A134', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A135', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A146', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png'), 
     array('code'=>'A165', 'image_url'=>'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png') 
    ); 

    if (count($products) > 0) { 
     $opts = array(
      'http'=>array(
       'protocol_version'=>'1.1', 
       'method'=>'GET', 
       'user_agent'=>'Image Resizer' 
      ) 
     ); 
     $context = stream_context_create($opts); 
     $def_width = 100; 
     $max_width = $def_width; 
     foreach($products as $product) { 
      $code = $product['code']; 
      $folder = substr($code, 0, 3); 
      echo('Looking at: ' .$product['code'] ."<br />"); 
      $file = '/tmp/' .$folder .'/' .$code .'_' .$def_width .'.jpg'; 
      $filemtime = @filemtime($file); 
      $gen_file = true; 
      if ($filemtime !== false) { 
       $file_age = (time() - $filemtime); 
       if ($file_age <= 300) { 
        $gen_file = false; 
       } 
      } 
      echo('&nbsp;&nbsp;&nbsp;&nbsp;File not cached or cached file has expired<br />'); 
      if ($gen_file) { 
       echo('&nbsp;&nbsp;&nbsp;&nbsp;Getting File...'); 
       $imgStr = file_get_contents($product['image_url'], false, $context); 
       $img = @imagecreatefromstring($imgStr); 
       if (is_resource($img)) { 
        echo('DONE' .'<br />'); 
        $image_x = imagesx($img); 
        $image_y = imagesy($img); 
        if ($def_width >= $image_x) { 
         $def_width = $image_x; 
        } 
        echo('&nbsp;&nbsp;&nbsp;&nbsp;Calculating Scale<br />'); 
        $ts = min($max_width/$image_x,$max_width/$image_y); 
        $thumbhght = $ts * $image_y; 
        $thumbwth = $ts * $image_x; 

        $thumb_image_resized = imagecreatetruecolor($thumbwth, $thumbhght); 
        imagecopyresampled($thumb_image_resized, $img, 0, 0, 0, 0, $thumbwth, $thumbhght, $image_x, $image_y); 
        echo('&nbsp;&nbsp;&nbsp;&nbsp;Checking For Directory<br />'); 
        if (!is_dir('/tmp/' .$folder)) { 
         mkdir('/tmp/' .$folder); 
        } 
        echo('&nbsp;&nbsp;&nbsp;&nbsp;Writing File<br />'); 
        $new_file = '/tmp/' .$folder .'/' .$code .'_' .$def_width .'.jpg'; 

        imagejpeg($thumb_image_resized, $new_file, 100); 
        echo('&nbsp;&nbsp;&nbsp;&nbsp;DONE<br />'); 

        imagedestroy($img); 
        imagedestroy($thumb_image_resized); 
       } else { 
        echo('Problem Getting Image<br />'); 
        die(); 
       } 
      } else { 
       echo('&nbsp;&nbsp;&nbsp;&nbsp;Already Exists<br />'); 
      } 
     } 
    } 
    $end_time = mktime(); 
    echo('Completed In...' .($end_time - $start_time) .' seconds(s)<br />'); 

ответ

9

HTTP-запросы по умолчанию сконфигурированы по умолчанию. Если вы не используете «Соединение: Закрыть», он предполагает «Соединение: Keep-Alive», и вам нужно дождаться окончания соединения (так как вы никогда не закрывали его) до того, как начнется следующий цикл.

+0

Спасибо! Запросы, которые принимали 0,15 с HTTP 1.0, занимали не менее 5 с по HTTP 1.1. Простой заголовок («Соединение: закрыть»); починил это! – Mave

0

Ваш контекст говорит file_get_contents(), чтобы закрыть соединение HTTP каждый раз. Возможно, поэтому код занимает очень много времени, поскольку он закрывает и повторно открывает соединения много раз? Я не знаком с внутренними файлами file_get_contents(), но вы можете настроить контекст для использования «Connection: keep-alive» для всех, кроме последнего соединения, и «Connection: close» для последнего.

+1

Я бы ожидал 'file_get_contents()', чтобы закрыть его соединение независимо - он закрывает дескрипторы файлов при чтении файлов с диска. Если вы хотите производительность, cURL - лучшая ставка. Вы можете снова и снова использовать один и тот же румяный инструмент; подключение сохраняется по умолчанию, если я правильно помню. –

+0

Я согласен с вами в использовании cURL, если нет причин, по которым dorgan должен использовать file_get_contents(). –

 Смежные вопросы

  • Нет связанных вопросов^_^