Skip to content

Commit 905aefd

Browse files
authored
use time.time_ns() for better precision (#202)
Signed-off-by: Inada Naoki <[email protected]>
1 parent f3bc435 commit 905aefd

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
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

+10-4
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,21 @@ def close(): # pragma: no cover
3030

3131

3232
class EventTime(msgpack.ExtType):
33-
def __new__(cls, timestamp):
33+
def __new__(cls, timestamp, nanoseconds=None):
3434
seconds = int(timestamp)
35-
nanoseconds = int(timestamp % 1 * 10**9)
35+
if nanoseconds is None:
36+
nanoseconds = int(timestamp % 1 * 10**9)
3637
return super().__new__(
3738
cls,
3839
code=0,
3940
data=struct.pack(">II", seconds, nanoseconds),
4041
)
4142

43+
@classmethod
44+
def from_unix_nano(cls, unix_nano):
45+
seconds, nanos = divmod(unix_nano, 10**9)
46+
return cls(seconds, nanos)
47+
4248

4349
class FluentSender:
4450
def __init__(
@@ -78,7 +84,7 @@ def __init__(
7884

7985
def emit(self, label, data):
8086
if self.nanosecond_precision:
81-
cur_time = EventTime(time.time())
87+
cur_time = EventTime.from_unix_nano(time.time_ns())
8288
else:
8389
cur_time = int(time.time())
8490
return self.emit_with_time(label, cur_time, data)
@@ -129,7 +135,7 @@ def close(self):
129135

130136
def _make_packet(self, label, timestamp, data):
131137
if label:
132-
tag = ".".join((self.tag, label)) if self.tag else label
138+
tag = f"{self.tag}.{label}" if self.tag else label
133139
else:
134140
tag = self.tag
135141
if self.nanosecond_precision and isinstance(timestamp, float):

0 commit comments

Comments
 (0)