XCode 6 Playground Measuring Code Performance

2019-02-22 04:53发布

问题:


Is there any quick way of evaluating the performance / runtime of a certain code part written in the new XCode 6 playground?
I want to start learning Swift by comparing different coding styles for certain solutions and their impact on the code performance.

回答1:

We strongly discourage using playgrounds to measure performance, at least using time as your measure of performance. By far the majority of the time taken during a playground is the logging of results to display in the sidebar; the actual time your code takes doesn't contribute as much. So the runtime of your code in a playground will mostly depend on how many lines of code are run / results are logged.

If you want to do performance measurements, check out the XCTest framework. You can create a test bundle for your swift code.

One thing you can measure in a playground is the number of times your lines of code are run. So if, for example, you're trying to measure the algorithmic complexity of some code, you could do that based on how many times it needs to run lines of code to e.g. complete a sort, or whatever it is you're trying to do. Lines of code that are run more than once displays the number of times they are run in the results sidebar.



回答2:

I built this little tool that allows you to have performance testing in your Playground.

I'll continue to update and enhance it, but for now, it'll give you the basic ability to measure how long a function takes to run.

https://github.com/sebastienpeek/swift-performance



回答3:

I have found one (maybe not so elegant) solution:

var start = TickCount()

var implicitInteger = 0
for (var i = 1; i < 500; i++) {
    implicitInteger += i;
}

var end = TickCount()
var dur = end - start


The variable 'dur' gives you the ticks your code needed to execute.