How to make Playground execution time is as fast a

2020-02-29 03:34发布

问题:

I see that playground execution speed is not reliable. For example with a code:

import UIKit
var count = 0;

let startTime = NSDate()
for i in 1...10000 {
   count++
}
let endTime = NSDate()

let interval = endTime.timeIntervalSinceDate(startTime)

the value of interval is about 2s, which is not reliable. With the release of Swift 2.0 & XCode beta 7, is it possible to make swift playground code execute as fast as in iOS application?

回答1:

There's a workaround thanks to the Sources folder of the Playground.

You can either use the menu to add external files:

New > Add files to sources

or go to menu:

View > Navigators > Show project navigator

and drop a .swift file in the Sources folder.

To be accessible, your code in this folder has to be public:

public class PlayGround {
    public class func count() {
        var count = 0
        for i in 1...10000 {
            count++
        }
    }
}

Then it's as usual in the Playground itself:

let startTime = NSDate()

PlayGround.count()

let endTime = NSDate()

let interval = endTime.timeIntervalSinceDate(startTime) // 0.0062