<getTimeMillis()> is deprecated. Is there an alter...
# kotlin-native
a
getTimeMillis() is deprecated. Is there an alternative? I was using it to generate a temporary directory for tests. This was handy because I could check the test output, and the directories would be ordered no matter how many times I ran the test
a
That would probably work, but I’d prefer not adding a library just for a single function :)
after a quick test this seems to work (using Kotlin 1.9)
Copy code
private fun systemTimeMillis(): Long {
  return memScoped {
    val timespec = alloc<platform.posix.timespec>().ptr
    platform.posix.clock_gettime(platform.posix.CLOCK_REALTIME.convert(), timespec)
    @OptIn(UnsafeNumber::class)
    timespec.pointed
      .run { tv_sec.seconds + tv_nsec.nanoseconds }
      .inWholeMilliseconds
  }
}
and for seconds:
Copy code
private fun systemTimeSeconds(): Long {
  return memScoped {
    val time = alloc<LongVar>()
    platform.posix.time(time.ptr)
    time.value
  }
}
r
Why don't you just use what the deprecation notice tells you to use?
o
Because in deprecation notice mentioned not a direct replacement, and only suggests on how to measure
Duration
between to points in time. What is needed here is to get sorted identifier - time in millis from some point in time which will work between runs of multiple instances of application, not inside one application So, there is no direct simple replacement in stdlib for this 🙂 only in kotlinx.datetime, or via platform capabilities (code which mentioned above)
e
(
gettimeofday
is older and available on more platforms than
clock_gettime
but I don't think it matters for kotlin's targets)
a
I saw some mention of
gettimeofday
in some StackOverflow answers, but Kotlin doesn’t include it by default - I got
Unresolved reference: gettimeofday