Skip to content

Commit 2a9199b

Browse files
committed
use time.time_ns() for better precision
Signed-off-by: Inada Naoki <[email protected]>
1 parent f3bc435 commit 2a9199b

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

fluent/event.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import time
2-
31
from fluent import sender
42

53

64
class Event:
75
def __init__(self, label, data, **kwargs):
86
assert isinstance(data, dict), "data must be a dict"
97
sender_ = kwargs.get("sender", sender.get_global_sender())
10-
timestamp = kwargs.get("time", int(time.time()))
11-
sender_.emit_with_time(label, timestamp, data)
8+
timestamp = kwargs.get("time", None)
9+
if timestamp is not None:
10+
sender_.emit_with_time(label, timestamp, data)
11+
else:
12+
sender_.emit(label, data)

fluent/sender.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,23 @@ def close(): # pragma: no cover
3030

3131

3232
class EventTime(msgpack.ExtType):
33-
def __new__(cls, timestamp):
34-
seconds = int(timestamp)
35-
nanoseconds = int(timestamp % 1 * 10**9)
33+
def __new__(cls, timestamp, nanoseconds=None):
34+
if nanoseconds is None:
35+
seconds = int(timestamp)
36+
nanoseconds = int(timestamp % 1 * 10**9)
37+
else:
38+
seconds = int(timestamp)
3639
return super().__new__(
3740
cls,
3841
code=0,
3942
data=struct.pack(">II", seconds, nanoseconds),
4043
)
4144

45+
@classmethod
46+
def from_unix_nano(cls, unix_nano):
47+
seconds, nanos = divmod(unix_nano, 10**9)
48+
return cls(seconds, nanos)
49+
4250

4351
class FluentSender:
4452
def __init__(
@@ -78,7 +86,7 @@ def __init__(
7886

7987
def emit(self, label, data):
8088
if self.nanosecond_precision:
81-
cur_time = EventTime(time.time())
89+
cur_time = EventTime.from_unix_nano(time.time_ns())
8290
else:
8391
cur_time = int(time.time())
8492
return self.emit_with_time(label, cur_time, data)
@@ -129,7 +137,7 @@ def close(self):
129137

130138
def _make_packet(self, label, timestamp, data):
131139
if label:
132-
tag = ".".join((self.tag, label)) if self.tag else label
140+
tag = f"{self.tag}.{label}" if self.tag else label
133141
else:
134142
tag = self.tag
135143
if self.nanosecond_precision and isinstance(timestamp, float):

0 commit comments

Comments
 (0)