Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use time.time_ns() for better precision #202

Merged
merged 1 commit into from Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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