Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add ability to measure a single callable and get result #48077

Merged
merged 2 commits into from Aug 17, 2023

Conversation

timacdonald
Copy link
Member

@timacdonald timacdonald commented Aug 16, 2023

Gives the ability to measure a given callable inline and allow receive the resulting value, e.g.

[$result, $duration] = Benchmark::once(function () {
    sleep(1);

    return 'foo';
});

Useful for providing metrics around different execution paths of your application.

@nunomaduro
Copy link
Member

@timacdonald Can you give me a real world use case where you would want to see the result?

@taylorotwell taylorotwell merged commit e766200 into laravel:10.x Aug 17, 2023
14 checks passed
@timacdonald
Copy link
Member Author

timacdonald commented Aug 17, 2023

Sure thing.

Measuring and logging external service interactions for alerting

public function list()
{
    [$response, $duration] = Benchmark::value(fn () => Http::get('https://external-service.com/list.json'));

    if ($duration > 1000) {
      Log::warning('external-service.com is running slow');
    }

    return $response->json();
}

Adding "Server-Timing" headers

public function index()
{
    [$users, $dataDuration] = Benchmark::value(function () {
        $users = DB::where(...)->get();

        return $users->map(...);
    });

    [$response, $responseDuration] = Benchmark::value(fn () => UserResource::collection($users)->response());

    return $response->header('Server-Timing', "db;dur={$dataDuration}, response;dur={$responseDuration}");
}

Monitoring the duration of different execution paths and external service interactions is a common pattern, in my own experience, for application logging, monitoring, and metrics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants