testing promises with php
This commit is contained in:
commit
3a4b04c1ec
|
@ -0,0 +1,2 @@
|
|||
vendor/
|
||||
composer.lock
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"require": {
|
||||
"guzzlehttp/guzzle": "^6.4"
|
||||
},
|
||||
"autoload": {
|
||||
"files": ["lib.php"]
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
// https://xrg.io/tests/promises
|
||||
|
||||
require_once(dirname(__FILE__) .'/vendor/autoload.php');
|
||||
|
||||
// lib.php, helper functions
|
||||
Lib\plain();
|
||||
Lib\printf('load');
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Promise;
|
||||
use GuzzleHttp\Pool;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use GuzzleHttp\Promise\EachPromise;
|
||||
|
||||
Lib\printf('client');
|
||||
|
||||
$client = new Client();
|
||||
|
||||
Lib\printf('requests');
|
||||
|
||||
$requests = function ($n) use ($client) {
|
||||
$uri = 'https://xrg.io/tests/promises/sleep.php?';
|
||||
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
yield function() use ($client, $uri, $i) {
|
||||
return $client->getAsync($uri . http_build_query(['o' => $i, 's' => random_int(1, 5)]));
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
Lib\printf('pool');
|
||||
|
||||
$pool = new Pool($client, $requests(3), [
|
||||
'concurrency' => 5,
|
||||
'fulfilled' => function ($response, $index) {
|
||||
Lib\printf(' i='. $index .' '. $response->getBody());
|
||||
},
|
||||
'rejected' => function ($reason, $index) {
|
||||
Lib\printf(' '. $index .' '. $reason);
|
||||
},
|
||||
]);
|
||||
|
||||
Lib\printf('promise');
|
||||
// Initiate the transfers and create a promise
|
||||
$promise = $pool->promise();
|
||||
|
||||
Lib\printf('wait');
|
||||
// Force the pool of requests to complete.
|
||||
$promise->wait();
|
||||
|
||||
Lib\printf('end');
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace Lib;
|
||||
|
||||
function microtime_calc(): array
|
||||
{
|
||||
static $last = null; // 1st time
|
||||
static $sum = 0.0; // 1st time
|
||||
$mt = microtime(true);
|
||||
$diff = is_null($last)? 0.0: bcsub($mt, $last);
|
||||
$sum = bcadd($sum, $diff);
|
||||
$last = $mt;
|
||||
return [$sum, $diff];
|
||||
}
|
||||
|
||||
function printf(string $str, ...$args): int
|
||||
{
|
||||
return \printf("∑%.6f +%.6f | ". $str."\n", ...microtime_calc(), ...$args);
|
||||
}
|
||||
|
||||
function plain(): void
|
||||
{
|
||||
header('Content-Type: text/plain');
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
<?php
|
||||
|
||||
$s = ((int)$_GET['s']?: random_int(2, 5));// * 1000000;
|
||||
sleep($s);
|
||||
//printf("\$µs=%d", $s);
|
||||
printf("\$s=%d", $s);
|
Loading…
Reference in New Issue