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

Getting the response time? #1464

Closed
resal81 opened this issue Jan 6, 2023 · 2 comments
Closed

Getting the response time? #1464

resal81 opened this issue Jan 6, 2023 · 2 comments

Comments

@resal81
Copy link

resal81 commented Jan 6, 2023

Thanks for this great library. Is there a recommended way to get/log the response time for a request? One way would be to calculate the time in the handler, but not sure how to access it in the logger function.

@yhirose
Copy link
Owner

yhirose commented Jan 10, 2023

@resal81, sorry for the late reply.

If you are talking about client call, you can simply do the following.

auto start = std::chrono::system_clock::now();
cli.Get(...);
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
// Format and output `elapsed`...

But if you are talking about service side, there is no easy way to log response time. The only think that I can come up with is to make your own TaskQueue class and measure duration time as below.

class ThreadPoolTaskQueueWithResponseTimeCalculation : public TaskQueue {
public:
  ThreadPoolTaskQueueWithResponseTimeCalculation(size_t n) {
    pool_.start_with_thread_count(n);
  }

  virtual void enqueue(std::function<void()> fn) override {
    pool_.enqueue([fn]() {
      auto start = std::chrono::system_clock::now();
      fn();
      auto end = std::chrono::system_clock::now();
      auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
      // Format and output `elapsed`...
    });
  }

  virtual void shutdown() override {
    pool_.shutdown_gracefully();
  }

private:
  YourThreadPool pool_;
};

svr.new_task_queue = [] {
  return new ThreadPoolTaskQueueWithResponseTimeCalculation(12);
};

I know cpp-httplib lacks a good logging facility like #870. But hope the above workaround can help you for now.

@yhirose yhirose closed this as completed Jan 10, 2023
@resal81
Copy link
Author

resal81 commented Jan 18, 2023

Yes, I meant for the server side. Thanks for the detailed answer!

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

No branches or pull requests

2 participants