Skip to content

Commit

Permalink
use time.time_ns() for better precision (#202)
Browse files Browse the repository at this point in the history
Signed-off-by: Inada Naoki <songofacandy@gmail.com>
  • Loading branch information
methane committed Feb 29, 2024
1 parent f3bc435 commit 905aefd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
9 changes: 5 additions & 4 deletions fluent/event.py
@@ -1,11 +1,12 @@
import time

from fluent import sender


class Event:
def __init__(self, label, data, **kwargs):
assert isinstance(data, dict), "data must be a dict"
sender_ = kwargs.get("sender", sender.get_global_sender())
timestamp = kwargs.get("time", int(time.time()))
sender_.emit_with_time(label, timestamp, data)
timestamp = kwargs.get("time", None)
if timestamp is not None:
sender_.emit_with_time(label, timestamp, data)
else:
sender_.emit(label, data)
14 changes: 10 additions & 4 deletions fluent/sender.py
Expand Up @@ -30,15 +30,21 @@ def close(): # pragma: no cover


class EventTime(msgpack.ExtType):
def __new__(cls, timestamp):
def __new__(cls, timestamp, nanoseconds=None):
seconds = int(timestamp)
nanoseconds = int(timestamp % 1 * 10**9)
if nanoseconds is None:
nanoseconds = int(timestamp % 1 * 10**9)
return super().__new__(
cls,
code=0,
data=struct.pack(">II", seconds, nanoseconds),
)

@classmethod
def from_unix_nano(cls, unix_nano):
seconds, nanos = divmod(unix_nano, 10**9)
return cls(seconds, nanos)


class FluentSender:
def __init__(
Expand Down Expand Up @@ -78,7 +84,7 @@ def __init__(

def emit(self, label, data):
if self.nanosecond_precision:
cur_time = EventTime(time.time())
cur_time = EventTime.from_unix_nano(time.time_ns())
else:
cur_time = int(time.time())
return self.emit_with_time(label, cur_time, data)
Expand Down Expand Up @@ -129,7 +135,7 @@ def close(self):

def _make_packet(self, label, timestamp, data):
if label:
tag = ".".join((self.tag, label)) if self.tag else label
tag = f"{self.tag}.{label}" if self.tag else label
else:
tag = self.tag
if self.nanosecond_precision and isinstance(timestamp, float):
Expand Down

0 comments on commit 905aefd

Please sign in to comment.