4

Several threads on stackoverflow (e.g. this one) discuss the different optimization levels (Onone, O, Ounchecked...) when compiling Swift applications.

However, those postings are related to the development on OSX. It seems that those optimizations can be set directly via Xcode or xcrun (xcrun swift -O3).

I'm wondering how to switch the different optimization levels when using the Swift compiler directly on Linux (Ubuntu 15.10). Currently, I'm building the application just by invoking swift build as it is shown in the docs, but I found no way no change the optimization level.

Community
  • 1
  • 1
fxlae
  • 905
  • 8
  • 17
  • Possible duplicate of [How to build optimized version of Swift Package using the Swift Package Manager \`swift build\` command](https://stackoverflow.com/questions/39775937/how-to-build-optimized-version-of-swift-package-using-the-swift-package-manager) – Mike C. Jul 05 '17 at 22:02
  • @MikeC. how is this question a duplicatie if I asked it 9 months earlier than the one provided by you? – fxlae Jul 07 '17 at 22:45
  • Both questions ask how to specify the swift compiler optimization level and even though the linked question is asked more recently it has a more accurate ("better") selected answer for the current version of the swift package maker (not a workaround). In other words, the other question/answer better serves the community (IMHO). – Mike C. Jul 09 '17 at 03:03
  • @MikeC. Okay, thanks for explaining. – fxlae Jul 09 '17 at 08:48

1 Answers1

4

It is possible to provide the -O, -Onone, and -Ounchecked optimization flags to the Swift compiler, swiftc. However, it appears that there is currently no way to specify additional flags to swift build. See, for example, the following link, even though it is not directly related: https://bugs.swift.org/browse/SR-397. The same bug report suggests that the team is actively working on adding this missing functionality.

One way that I found to work around the problem is to run swift build -v, find the first command that references -Onone, copy it and all the commands that follow it to a shell script, edit the script to use the desired optimization level instead of -Onone, and run the script. This should re-compile the Swift sources using the desired optimization level and rebuild the executable.

In my testing I found that a simple example involving sorting an array runs a couple of orders of magnitude faster if built using -O or -Ounchecked instead of -Onone.

Anatoli P
  • 4,791
  • 1
  • 18
  • 22
  • Thanks, that's a good workaround. In my tests, `-Ounchecked` was around 4% faster than `-O` in a quicksort implementation and around 19% faster in a genetic algorithm for solving TSPs. Compared to some older results on stack overflow, I think that `-O` got some nice improvements in the meantime. – fxlae Jan 06 '16 at 14:52