Why is Swift so slow (timeout) in compiling this code?

Also, using mmap means... well, that you need mmap.

That takes you out of the domain of pure-Swift code and introduces an OS dependency. Now you need to do this whole dance to make your code portable:

#if canImport(Darwin)
  import Darwin
#elseif canImport(Glibc)
  import Glibc
#elseif canImport(WasiLibc)
  ... etc

Also, Windows apparently doesn't have mmap, but has a similar function called MapViewOfFile. So you'll need to deal with that, too.

Alternatively, that static data could just live in the binary, and you could just access it like a regular Swift array without bothering with any of this.

Of course, there are other considerations which might cause you to want to split the data as a separate file which you load at runtime. Compile time shouldn't be one of those considerations, IMO.

4 Likes

My results on Intel MacBook, Xcode 14.1

% time swiftc -o app big_qs.swift
swiftc -o app big_qs.swift  38.93s user 3.43s system 98% cpu 42.823 total

And if patched with

- let vector = [
+ let vector = [Int](arrayLiteral:
% time swiftc -o app fix_qs.swift
swiftc -o app fix_qs.swift  14.71s user 6.61s system 98% cpu 21.629 total
% swiftc -version
swift-driver version: 1.62.15 Apple Swift version 5.7.1 (swiftlang-5.7.1.135.3 clang-1400.0.29.51)
Target: x86_64-apple-macosx12.0

Adding optimizations:

% time swiftc -O -o app big_qs.swift
swiftc -O -o app big_qs.swift  188.67s user 5.51s system 99% cpu 3:15.38 total
% time swiftc -O -o app fix_qs.swift
swiftc -O -o app fix_qs.swift  15.77s user 6.09s system 99% cpu 21.967 total

2 Likes

Thanks for testing out. Surprising that it looks to work on Intel but not on my M1. The first one still fails; and the second one does work but the output shows that only 16959 numbers were taken into consideration.

time swift run
Building for debugging...
[3/3] Linking swiftqs
Build complete! (31.30s)
16959 16959
swift run  0.09s user 0.02s system 0% cpu 31.635 total

It seems this is pretty much the only way that works very well taking all the 999999 numbers into consideration.

swift run
Building for debugging...
[3/3] Linking swiftqs
Build complete! (0.58s)
999999 999999
3 Likes

Uh, nice catch. It is the same for me.

1 Like