2

I'm playing with Swift for the first time and have some decent programs running under Ubuntu and on a Raspberry Pi but I cannot find a way to measure elapsed time. My first thought is to read the unix time but I cannot see it in any API and haven't figured out the FFI yet.

How should I measure elapsed time in Swift code on Ubuntu and Raspberry Pi?

J D
  • 48,105
  • 13
  • 171
  • 274
  • 2
    What's wrong with `Date`? – rmaddy Jan 02 '18 at 22:04
  • 1
    If you need accurate elapsed time, consider `mach_absolute_time` as outlined in [Technical Q&A 1398](https://developer.apple.com/library/content/qa/qa1398/_index.html). – Rob Jan 02 '18 at 22:20
  • Is NSDate an option? It is mentioned in this answer: [Measure elapsed time in swift](https://stackoverflow.com/a/24755958/3112672) – absmiths Jan 02 '18 at 22:40
  • My answer was converted into a comment so it can't be selected as an answer. That is not right. – absmiths Jan 02 '18 at 22:41
  • @absmiths - Effective with Swift 3, we don’t use `NSDate` anymore. We use `Date` nowadays. – Rob Jan 02 '18 at 22:42
  • What about the edit on the referenced answer to use DispatchTime.now()? Is that available outside of iOS? – absmiths Jan 02 '18 at 22:43
  • @absmiths `NSDate` won't compile on Linux. You can check out some server side swift projects that are heavy in date/time management. This is one of them https://github.com/BrettRToomey/Jobs – JustinM Jan 02 '18 at 22:45

1 Answers1

1

C is interoperable with Swift. If you don't want to use Foundation's Date as rmaddy suggested,* you should be able to call the C stdlib's time() function. Just import GlibC first.


*The Unix time from a Date is just Date.timeIntervalSince1970.

jscs
  • 63,694
  • 13
  • 151
  • 195