Skip to content

Commit

Permalink
avoid timer printing allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
arnetheduck committed Jun 19, 2024
1 parent 7052a12 commit 7ebdbe4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
13 changes: 8 additions & 5 deletions chronos/timer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -370,22 +370,25 @@ template add(a: var string, b: Base10Buf[uint64]) =
for index in 0 ..< b.len:
a.add(char(b.data[index]))

func pretty*(a: timer.Duration, parts = int.high): string =
func toString*(a: timer.Duration, parts = int.high): string =
## Returns a pretty string representation of Duration ``a`` - the
## number of parts returned can be limited thus truncating the output to
## an approximation that grows more precise as the duration becomes smaller
var
res = ""
res = newStringOfCap(32)
v = a.nanoseconds()
parts = parts

template f(n: string, T: Duration) =
if parts <= 0:
return res

if v >= T.nanoseconds():
res.add($(uint64(v div T.nanoseconds())))
res.add(Base10.toBytes(uint64(v div T.nanoseconds())))
res.add(n)
v = v mod T.nanoseconds()
dec parts
if v == 0 or parts <= 0:
if v == 0:
return res

f("w", Week)
Expand All @@ -401,7 +404,7 @@ func pretty*(a: timer.Duration, parts = int.high): string =

func `$`*(a: Duration): string {.inline.} =
## Returns string representation of Duration ``a``.
a.pretty()
a.toString()

func `$`*(a: Moment): string {.inline.} =
## Returns string representation of Moment ``a`` as nanoseconds value.
Expand Down
3 changes: 3 additions & 0 deletions tests/testtime.nim
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ suite "Asynchronous timers & steps test suite":
$nanoseconds(1_000_000_900) == "1s900ns"
$nanoseconds(1_800_700_000) == "1s800ms700us"
$nanoseconds(1_800_000_600) == "1s800ms600ns"
nanoseconds(1_800_000_600).toString(0) == ""
nanoseconds(1_800_000_600).toString(1) == "1s"
nanoseconds(1_800_000_600).toString(2) == "1s800ms"

test "Asynchronous steps test":
var fut1 = stepsAsync(1)
Expand Down

0 comments on commit 7ebdbe4

Please sign in to comment.