Search code examples
phpphp-ziparchive

Does ZipArchive::addFile() mess with hrtime()?


I have this loop:

//open archive $zip
$start = hrtime(true);
while(true) {
  $zip->addFile($files[$i++]);
  $end = hrtime(true);
  $time = ($end - $start) / 1e+9; // convert to seconds
  if( $time > 10.0) {
    break;
  }
}
echo $i;

I found that the timer does not accurately stops after 10sec. Whereas if I replace the loop with the following:

//open archive $zip
$start = hrtime(true);
while(true) {
  sleep(1); // simulate work

  $end = hrtime(true);
  $time = ($end - $start) / 1e+9; // convert to seconds
  if( $time > 10.0) {
    break;
  }
}
echo $i;

The loop does stop after 10 or more seconds. Is ZipArchive::addFile() doing something to the hardware timer the prevents predicting proper time difference? I understand I could use microtime(true) but I understand it might be even less accurate in VM environments.


Solution

  • sorry for delay....

    the method addFile return true or false based on the file's stats. so yes the result is returned asynchronously

    than the file is added to a queue and all queued files are added synchronously so no the method it is not asynchronous

    if you need to wait for each file to be completely loaded before loading the next one a good workaround is open and close your zip every time you add a new file. since $zip->close() will wait until all operations are done

    check and test this and tell me if do the job:

    $zip = new ZipArchive;
    //replace this with your zip file name========
    $zipName="./test.zip";//======================
    //============================================
    
    
    //dummy data===================================
    //those are the files that i've used for test 
    //of course you need to remove this part
    $files=[];
    for($i=0;$i<99;$i++){
        $files[$i]="./bins/".$i.".bin";
    }
    //=============================================
    
    
    //===================
    $i=0;//init $i if you have't done it before
    $start = hrtime(true);
    while(true) {
        $zip->open($zipName,ZipArchive::CREATE);
        $zip->addFile($files[$i++]);
        $end = hrtime(true);
       
        $zip->close();
        $time = ($end - $start) / 1e+9; // convert to seconds
    
        //this is just for log remove it if you don't need it ========================
        echo "Step {$i}:( i:{$i}; time:{$time} )\n<br>\n";
        echo "\n<br>\n";
        //=======================================================================
    
    
        if( $time > 10.0) {
            break;
        }
        $i++;
    }
    
    //this is just for log remove it if you don't need it ========================
    sleep(5);
    $end = hrtime(true);
    $time = ($end - $start) / 1e+9; // convert to seconds
    echo "end here:( time:{$time};  start:{$start};  end:{$end}; \n<br>\n";
    //=========================================================