Skip to content

Commit 5dc2de1

Browse files
committed
rpc: speedup Connection::get_date_time
1 parent 66bc87d commit 5dc2de1

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

silkworm/rpc/http/connection.cpp

+30-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include <array>
2020
#include <chrono>
2121
#include <exception>
22+
#include <shared_mutex>
2223
#include <string_view>
2324

2425
#include <boost/asio/buffer.hpp>
@@ -441,11 +442,38 @@ bool Connection::is_method_allowed(boost::beast::http::verb method) {
441442

442443
std::string Connection::get_date_time() {
443444
static const absl::TimeZone kTz{absl::LocalTimeZone()};
444-
const absl::Time now{absl::Now()};
445+
static std::pair<int64_t, std::string> cache;
446+
static std::shared_mutex cache_mutex;
447+
448+
// read cache
449+
std::pair<int64_t, std::string> result;
450+
{
451+
std::shared_lock lock{cache_mutex};
452+
result = cache;
453+
}
454+
455+
const int64_t ts = absl::ToUnixSeconds(absl::Now());
456+
457+
// if timestamp matches - return the cached result
458+
if (ts == result.first) {
459+
return std::move(result.second);
460+
}
445461

462+
// otherwise - format
463+
const absl::Time now = absl::FromUnixSeconds(ts);
446464
std::stringstream ss;
447465
ss << absl::FormatTime("%a, %d %b %E4Y %H:%M:%S ", now, kTz) << kTz.name();
448-
return ss.str();
466+
result = {ts, ss.str()};
467+
468+
// update cache if timestamp increased
469+
{
470+
std::unique_lock lock{cache_mutex};
471+
if (ts > cache.first) {
472+
cache = result;
473+
}
474+
}
475+
476+
return std::move(result.second);
449477
}
450478

451479
Task<void> Connection::compress(const std::string& clear_data, std::string& compressed_data) {

0 commit comments

Comments
 (0)