0

I'm mucking around with the beta of the IBM Swift Sandbox; does anyone know why I'm getting the following error for the code below?:

LLVM ERROR: Program used external function 'CFAbsoluteTimeGetCurrent' which could not be resolved!

// A demonstration of both iterative and recursive algorithms for computing the Fibonacci numbers.

import CoreFoundation

// A recursive algorithm to compute the Fibonacci numbers.
func fibRec (n : Int) -> Double {
    return (Double)(n < 3 ? 1 : fibRec(n - 1) + fibRec(n - 2))
}

// An iterative algorithm to compute the Fibonacci numbers.
func fibIter (n : Int) -> Double {
    var f2 = 0.0
    var f1 = 1.0
    var f0 = 1.0

    for _ in 0 ..< n {
        f2 = f1 + f0
        f0 = f1
        f1 = f2
    }
    return f0
}

// Initialise array to hold algorithm execution times.
var fibTimes = [Double]()

// i is the ith Fibonacci number to be computed.
for i in 120..<129 {

    var fibNum = 0.0
    var fibSum = 0.0

    // j is the number of times to compute F(i) to obtain average.
    for j in 0..<5 {

        // Set start time.
        let startTime = CFAbsoluteTimeGetCurrent()

        // Uses the recursive algorithm.
        //                fibNum = fibRec(i)

        // Uses the iterative algorithm.
        fibNum = fibIter(i)
        fibTimes.insert(CFAbsoluteTimeGetCurrent() - startTime, atIndex: j)
    }

    // Compute the average execution time.
    for p in fibTimes {
        fibSum += p
    }
    fibSum = fibSum / 5

    print("Fibonacci number \(i) is: \(fibNum)")
    print("Execution time:         \(fibSum) seconds")
}
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
John Reynolds
  • 79
  • 1
  • 2
  • 10
  • `import Foundation` as well... Don't know exactly why this is needed (anyone?), but checked it a minute ago and it's working – Alladinian Dec 05 '15 at 14:32
  • @Alladinian You should make an answer, this is the solution. – Eric Aya Dec 05 '15 at 20:15
  • 1
    @EricD. Done. I was hesitant at first since I could not provide a real explanation on why this is working, but I guess a half-answer is better than no answer at all. – Alladinian Dec 05 '15 at 20:25

2 Answers2

3

You just have to import Foundation as well.

I am not sure why this is needed (I hope someone that does know, could shed some light on this), but it works.

Alladinian
  • 34,483
  • 6
  • 89
  • 91
0

To clarify, you have to import them both.

import Foundation
import CoreFoundation

Alternatively, Glibc has clock() which returns an Int instead. For example:

import Glibc
struct StartTimer {
    let start = clock()
    var elapsed = -1
    mutating func stop() { elapsed = clock() - start }
}

var timer = StartTimer()
/* do your work */
timer.stop()
print("Elapsed Time: \(timer.elapsed)")
adazacom
  • 443
  • 3
  • 9