Skip to content

Fix timestamp comparison - #1038

Merged
csmarchbanks merged 1 commit into
prometheus:masterfrom
magmax:master
May 28, 2024
Merged

Fix timestamp comparison#1038
csmarchbanks merged 1 commit into
prometheus:masterfrom
magmax:master

Conversation

@magmax

@magmax magmax commented May 27, 2024

Copy link
Copy Markdown
Contributor

Fixes #1037, where comparison between Timestamp were wrong.

I've chosen this solution after testing different ones because it is the faster one. Files and speed tests here.

Different implementations:

Changing the full class by a namedtuple

from collections import namedtuple

class TimestampNamedtuple(namedtuple("Timestamp", ["sec", "nsec"])):
    """A nanosecond-resolution timestamp."""

    def __new__(cls, sec: float, nsec: float) -> None:
        if nsec < 0 or nsec >= 1e9:
            raise ValueError(f"Invalid value for nanoseconds in Timestamp: {nsec}")
        if sec < 0:
            nsec = -nsec
        return super().__new__(cls, int(sec), int(nsec))

    def __str__(self) -> str:
        return f"{self.sec}.{self.nsec:09d}"

    def __repr__(self) -> str:
        return f"Timestamp({self.sec}, {self.nsec})"

    def __float__(self) -> float:
        return float(self.sec) + float(self.nsec) / 1e9

Here there is no need to implement comparison operators because they are already implemented in the parent class.

This was the worse implementation, around 50% slower than the chosen one.

tuples

    def __gt__(self, other: "Timestamp") -> bool:
        return (self.sec, self.nsec) > (other.sec, other.nsec)

logical operators

    def __gt__(self, other: "Timestamp") -> bool:
        return self.sec > other.sec or (self.sec == other.sec and self.nsec > other.nsec)
@magmax
magmax force-pushed the master branch 2 times, most recently from aa61325 to fd5c327 Compare May 28, 2024 05:07
Signed-off-by: Miguel Angel Garcia <miguelangel.garcia@gmail.com>

@csmarchbanks csmarchbanks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@csmarchbanks
csmarchbanks merged commit 09a5ae3 into prometheus:master May 28, 2024
btimby pushed a commit to btimby/client_python that referenced this pull request Aug 2, 2024
Signed-off-by: Miguel Angel Garcia <miguelangel.garcia@gmail.com>
Signed-off-by: Ben Timby <btimby@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants