Skip to content

Commit b72c41b

Browse files
committed
refactor: faster version of SetTimestamp()
1 parent 59f1a5b commit b72c41b

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

exporters/elasticsearch/src/es_log_recordable.cc

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33

44
#include <chrono>
55
#include <ctime>
6-
#include <iomanip>
76
#include <nlohmann/json.hpp>
8-
#include <sstream>
97
#include <string>
108

119
#include "opentelemetry/exporters/elasticsearch/es_log_recordable.h"
@@ -82,11 +80,14 @@ void ElasticSearchRecordable::SetTimestamp(
8280
std::chrono::duration_cast<std::chrono::microseconds>(timePoint.time_since_epoch()) %
8381
std::chrono::seconds(1);
8482

85-
std::ostringstream oss;
86-
oss << std::put_time(&tm, "%FT%T") << '.' << std::setw(6) << std::setfill('0')
87-
<< microseconds.count() << 'Z';
83+
// `sizeof()` includes the null terminator
84+
constexpr auto dateSize = sizeof("YYYY-MM-DDTHH:MM:SS.uuuuuuZ");
85+
char bufferDate[dateSize];
86+
auto offset = std::strftime(bufferDate, sizeof(bufferDate), "%Y-%m-%dT%H:%M:%S", &tm);
87+
std::snprintf(bufferDate + offset, sizeof(bufferDate) - offset, ".%06ldZ",
88+
static_cast<long>(microseconds.count()));
8889

89-
const std::string dateStr = oss.str();
90+
const std::string dateStr(bufferDate);
9091
#endif
9192

9293
json_["@timestamp"] = dateStr;

0 commit comments

Comments
 (0)