Skip to content

Conversation

@magmax
Copy link
Contributor

@magmax magmax commented May 27, 2024

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>
Copy link
Member

@csmarchbanks csmarchbanks left a comment

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Timestamp comparison is wrong

2 participants