我在这里寻求帮助,以了解我的代码是否正确。因为我看不出响应时间有多少改善。我用大口答应降低我的整体表现。
现有代码:
protected function sampleFunction(&$outputArray){
foreach($outputArray as $key => $images){
foreach($images as $index => $image){
$result = NewClass::ClassSampleFunction($image->path, $this->samplePoint); // This is expensive function calls in current code.
}
}
}
使用guzzle promise回调的新代码:
protected function sampleFunction(&$outputArray){
foreach($outputArray as $key => $images){
$promises = array();
foreach($images as $index => $image){
$promises[$index] = $this->promiseFunction($image,$index);
}
$results = \GuzzleHttp\Promise\settle($promises)->wait();
foreach ($results as $resultkey => $value) {
$search_point_image_xy_array = $value['value']->toArray();
// some logic to use result and put in another response array.
}
}
}
protected function promiseFunction($image,$index){
$promise = new Promise(
function () use ($image,$index,&$promise) {
$response = NewClass::ClassSampleFunction($image->path, $this->samplePoint);
$promise->resolve($response);
},
function () {
// do something that will cancel the promise computation (e.g., close
// a socket, cancel a database query, etc...)
}
);
return $promise;
}
这段新代码试图在NewClass::ClassSampleFunction($image->path, $this->samplePoint);
不使用外部端点的情况下使用耗时承诺来调用此昂贵的函数调用。但是在此之后,预计响应时间也会有所减少,但不会改变,而有时它会比旧代码更多。
提及NewClass::ClassSampleFunction($image->path, $this->samplePoint);
此运行的函数,假设我首先有一个for循环4范围,第二个每个有一个for循环10,然后总共有40次调用此函数。如果我使用了异步调用,那么第一次调用就没有了,第二次调用就结束了,反之亦然。这可以帮助在旧代码中使用等待时间
我做错了什么?任何帮助或建议吗?
最后,通过使用eachPromise
from,我可以在一定程度上提高性能guzzle/promise
。
修改代码:
protected function sampleFunction(&$outputArray){
foreach($outputArray as $key => $images){
$promises = array();
foreach($images as $index => $image){
$promises[$index] = $this->promiseFunction($image,$index);
}
$eachPromise = new EachPromise($promises, [
// how many concurrency we are use
'concurrency' => count($promises),
'fulfilled' => function ($response,$index) use (&$images, &$outputArray)
{
//logic for other operation.
},
'rejected' => function ($reason) {
}
]);
}
}
protected function promiseFunction($image,$index){
$promise = new Promise(
function () use ($image,$index,&$promise) {
$response = NewClass::ClassSampleFunction($image->path, $this->samplePoint);
$promise->resolve($response);
},
function () {
// do something that will cancel the promise computation (e.g., close
// a socket, cancel a database query, etc...)
}
);
return $promise;
}
参考文章:https : //medium.com/@ardanirohman/how-to-handle-async-request-concurrency-with-promise-in-guzzle-6-cac10d76220e
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句