浏览代码

Performance imporovement for Keep-Alive

yhirose 1 年之前
父节点
当前提交
cb74e4191b
共有 1 个文件被更改,包括 22 次插入4 次删除
  1. 22 4
      httplib.h

+ 22 - 4
httplib.h

@@ -3191,18 +3191,36 @@ private:
 #endif
 #endif
 
 
 inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
 inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
-  using namespace std::chrono;
-  auto timeout = keep_alive_timeout_sec * 1000;
-  auto start = steady_clock::now();
+  const auto timeout = keep_alive_timeout_sec * 1000;
+
+#ifdef CPPHTTPLIB_USE_STEADY_TIMER_FOR_KEEP_ALIVE
+  const auto start = std::chrono::steady_clock::now();
+#else
+  time_t elapse = 0;
+#endif
   while (true) {
   while (true) {
     auto val = select_read(sock, 0, 10000);
     auto val = select_read(sock, 0, 10000);
+
+#ifndef CPPHTTPLIB_USE_STEADY_TIMER_FOR_KEEP_ALIVE
+    elapse += 12; // heuristic...
+#endif
+
     if (val < 0) {
     if (val < 0) {
       return false;
       return false;
     } else if (val == 0) {
     } else if (val == 0) {
-      auto current = steady_clock::now();
+#ifdef CPPHTTPLIB_USE_STEADY_TIMER_FOR_KEEP_ALIVE
+      auto current = std::chrono::steady_clock::now();
       auto duration = duration_cast<milliseconds>(current - start);
       auto duration = duration_cast<milliseconds>(current - start);
       if (duration.count() > timeout) { return false; }
       if (duration.count() > timeout) { return false; }
+#else
+      if (elapse > timeout) { return false; }
+#endif
+
       std::this_thread::sleep_for(std::chrono::milliseconds{10});
       std::this_thread::sleep_for(std::chrono::milliseconds{10});
+
+#ifndef CPPHTTPLIB_USE_STEADY_TIMER_FOR_KEEP_ALIVE
+      elapse += 12; // heuristic...
+#endif
     } else {
     } else {
       return true;
       return true;
     }
     }