Search code examples
swiftmethodstimetimer

Measuring time between method "didUpdateValueFor" called


I want to measure the time between when a function is called, and the next time it is called.

Currently I have a app with bluetooth. Where a Arduino is sending a byte array to the app to be displayed in a tableview. I have two bluetooth modules which I want to measure time to see the difference in speed.

When the app receives a byte array, the function didUpdateValueFor is called. And in it it sends the data receives to another function.

My issues is that all the timers and counters I've used have only worked to get the whole execution time of the function.

All I want is to measure the time between the first byte array is received to the next packed is received.

func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print("Time elapsed for \(title): \(timeElapsed) s.")
}

Using a function that I've posted above I'm sure works great. But I want it to measure time between every time the didUpdateValueFor is called.

So:

Byte array receievd - didUpdateValueFor is called
Timer starts
New array received - didUpdateValueFor is called
Timebetween is: "...ms"

Solution

  • I actually found the answer. Not optimal but this works for now:

        var start = Date()
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        var diff = Date().timeIntervalSince(start)
        print("differanse is: \(diff) seconds")
        start = Date()
        print("Starting at 0")
        diff = 0
        print("diff = 0")
    

    Good enough