How to Convert Dispatchtimeinterval to Nstimeinterval (Or Double)

How to convert DispatchTimeInterval to NSTimeInterval (or Double)?

DispatchTimeInterval is a enum:

public enum DispatchTimeInterval : Equatable {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
case never
}

You can initialize DispatchTimeInterval using:

    let tenSeconds: DispatchTimeInterval = .seconds(10)
let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)

To get values from enum you need to match value with a case values in enum

    if case .seconds(let value) = tenSeconds {
print("DispatchTimeInterval is seconds \(value)")
} else if case .nanoseconds(let value) = tenNanoseconds {
print("DispatchTimeInterval is seconds \(value)")
}

Converting function might be look following:

func toDouble(_ interval: DispatchTimeInterval) -> Double? {
var result: Double? = 0

switch interval {
case .seconds(let value):
result = Double(value)
case .milliseconds(let value):
result = Double(value)*0.001
case .microseconds(let value):
result = Double(value)*0.000001
case .nanoseconds(let value):
result = Double(value)*0.000000001

case .never:
result = nil
}

return result
}

More about Enumeration see in Apple Documentation

UPDATE:

Create extension to DispatchTimeInterval

extension DispatchTimeInterval {
func toDouble() -> Double? {
var result: Double? = 0

switch self {
case .seconds(let value):
result = Double(value)
case .milliseconds(let value):
result = Double(value)*0.001
case .microseconds(let value):
result = Double(value)*0.000001
case .nanoseconds(let value):
result = Double(value)*0.000000001

case .never:
result = nil
}

return result
}
}

Create dispatch_time_t with NSTimeInterval

let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(0.3 * Double(NSEC_PER_SEC)))

dispatch_after(delayTime, dispatch_get_main_queue()) {
//... Code
}

You can try this, this works fine with me.

In your code just replace your last line with:

let d_time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeInterval * Double(NSEC_PER_SEC)))

Convert TimeInterval To String del String To Time Interval /del

Using calendar.dateComponents you can convert 915 to 00:15:15

func stringFromTimeInterval (interval: String) -> String {
let endingDate = Date()
if let timeInterval = TimeInterval(interval) {
let startingDate = endingDate.addingTimeInterval(-timeInterval)
let calendar = Calendar.current

var componentsNow = calendar.dateComponents([.hour, .minute, .second], from: startingDate, to: endingDate)
if let hour = componentsNow.hour, let minute = componentsNow.minute, let seconds = componentsNow.second {
return "\(hour):\(minute):\(seconds)"
} else {
return "00:00:00"
}

} else {
return "00:00:00"
}
}

Measure elapsed time in Swift

Update

With Swift 5.7, I think everything below becomes obsolete. Swift 5.7 introduces the concept of a Clock which appears to have a function designed to do exactly what is required here.

I'll update with an example as soon as I've got Swift 5.7 and have the time to rework it.


Here's a Swift function I wrote to measure Project Euler problems in Swift

As of Swift 3, there is now a version of Grand Central Dispatch that is "swiftified". So the correct answer is probably to use the DispatchTime API.

My function would look something like:

// Swift 3
func evaluateProblem(problemNumber: Int, problemBlock: () -> Int) -> Answer
{
print("Evaluating problem \(problemNumber)")

let start = DispatchTime.now() // <<<<<<<<<< Start time
let myGuess = problemBlock()
let end = DispatchTime.now() // <<<<<<<<<< end time

let theAnswer = self.checkAnswer(answerNum: "\(problemNumber)", guess: myGuess)

let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64)
let timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests

print("Time to evaluate problem \(problemNumber): \(timeInterval) seconds")
return theAnswer
}


Old answer

For Swift 1 and 2, my function uses NSDate:

// Swift 1
func evaluateProblem(problemNumber: Int, problemBlock: () -> Int) -> Answer
{
println("Evaluating problem \(problemNumber)")

let start = NSDate() // <<<<<<<<<< Start time
let myGuess = problemBlock()
let end = NSDate() // <<<<<<<<<< end time

let theAnswer = self.checkAnswer(answerNum: "\(problemNumber)", guess: myGuess)

let timeInterval: Double = end.timeIntervalSinceDate(start) // <<<<< Difference in seconds (double)

println("Time to evaluate problem \(problemNumber): \(timeInterval) seconds")
return theAnswer
}

Note that using NSdate for timing functions is discouraged: "The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.".



Related Topics



Leave a reply



Submit