note 129799 added to language.fibers
| From: | fibersare@cool.com | Date: | Thu, 10 Oct 2024 06:02:41 +0000 |
| Subject: | note 129799 added to language.fibers | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221586@lists.php.net to get a copy of this message | ||
From my observation you will not get any parallel benefit from Fibers unless you
Fiber::suspend() after some kind of system or server call. In other words, if you were
to Fiber::suspend() within the function passed to new Fiber before
$t = microtime(true), as opposed to after it, the code below would take one thousand
seconds, instead of just over one second. Also, note that main thread code will not run in parallel
unless all Fibers are started before any of the Fibers are resumed.
<?php
// 1000 Fibers that take one second individually can take about one second total along with the main
thread in parallel
$entireExecutionStartTime = microtime(true);
function createTimeoutFibers(int $count = 1, float $milliseconds = 1000):array{
$a = [];
$cF = function() use ($milliseconds):Fiber{
$f = new Fiber(function() use ($milliseconds){
$t = microtime(true); Fiber::suspend();
while(($q = microtime(true)-$t) < $milliseconds/1000){} // wait one second
return $q;
});
$f->start();
return $f;
};
for($i=0; $i<$count; $i++){
$a[] = $cF();
}
return $a;
}
// create an array of 1000 Fibers that each wait one second
$a = createTimeoutFibers(1000); $fiberExecutionTimes = [];
// wait one second on the main thread - to receive a main thread benefit this must occur after all
FiberInstance->start()s and before any FiberInstance->resume()s
$m = microtime(true);
while(microtime(true)-$m < 1){}
foreach($a as $f){
while(!$f->isTerminated()){
$f->resume();
}
$fiberExecutionTimes[] = $f->getReturn();
}
$entireExecutionTime = microtime(true)-$entireExecutionStartTime;
// easy to read output in $test
$test = '$fiberExecutionTimes = ['.join(', ', $fiberExecutionTimes).'];
$entireExecutionTime = '.$entireExecutionTime.';';
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.84.18 (proxied: 24.19.197.14)
----
Manual Page -- https://php.net/manual/en/language.fibers.php
Edit -- https://main.php.net/note/edit/129799
Del: integrated -- https://main.php.net/note/delete/129799/integrated
Del: useless -- https://main.php.net/note/delete/129799/useless
Del: bad code -- https://main.php.net/note/delete/129799/bad+code
Del: spam -- https://main.php.net/note/delete/129799/spam
Del: non-english -- https://main.php.net/note/delete/129799/non-english
Del: in docs -- https://main.php.net/note/delete/129799/in+docs
Del: other reasons-- https://main.php.net/note/delete/129799
Reject -- https://main.php.net/note/reject/129799
Search -- https://main.php.net/manage/user-notes.php