PHP code example of kmuenkel / parallel-collection

1. Go to this page and download the library: Download kmuenkel/parallel-collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kmuenkel / parallel-collection example snippets



$process1 = function () {
    sleep(5);   //Simulate taking a long time to handle the item
    return 'perform some long process';
};

$process2 = function () {
    sleep(5);   //Simulate taking a long time to handle the item
    return 'perform another long process';
};

$items = compact('process1', 'process1');

$before = now();
$results = collect($items)->mapToParallel()->toArray();
$after = now();

$elapsedTime = $after->diffInSeconds($before);
print_r(compact('results', 'elapsedTime'));

/**
 * Array:
 * (
 *    "results" => Array
 *    (
 *       ["process1"] => 'perform some long process'
 *       ["process2"] => 'perform another long process'
 *    )
 *    "elapsedTime" => 5
 * )
 */

$items = ['Hello', 'World'];
$handler = function (string $item) {
    sleep(5);   //Simulate taking a long time to handle the item

    return $item;
};

$before = now();
$results = collect($items)->mapToParallel($handler)->toArray();
$after = now();

$elapsedTime = $after->diffInSeconds($before);
print_r(compact('results', 'elapsedTime'));

/**
 * Array:
 * (
 *    "results" => Array
 *    (
 *       [0] => 'Hello'
 *       [1] => 'World'
 *    )
 *    "elapsedTime" => 5
 * )
 */