[swift-users] Why are Swift Loops slow?

Greg Parker gparker at apple.com
Wed Oct 12 05:05:14 CDT 2016


> On Oct 12, 2016, at 2:25 AM, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
> 
> uint64_t nbrBytes = 4e8;
> uint64_t count = 0;
> for( uint64_t byteIndex = 0; byteIndex < nbrBytes; byteIndex++ )
> {
> 	count += byteIndex;
> 	if ( ( byteIndex & 0xffffffff ) == 0 ) { count += 1.3; }  (AAA) 
> };
> 
> Takes 260 msec.
> 
> Btw.: Without the (AAA) line the whole loop is done in 10 μsec. A really clever compiler!
> And with “count += 1” instead of “count += 1.3” it takes 410 msec. Very strange. 
> But this is beside the point here.
> 
> 
> Now Swift:
> let nbrBytes = 400_000_000
> var count = 0
> for byteIndex in 0 ..< nbrBytes
> {
> 	count += byteIndex
> 	if ( ( byteIndex & 0xffffffff ) == 0 ) {count += Int(1.3);}
> }
> 
> takes 390 msec - about 50 % more.
> 
> Release build with default options.

You'll need to read the generated assembly code if you want to analyze performance of this sort of small arithmetic loop. Performance of this kind of code can be greatly affected by small optimization changes.

clang's `count +=1` code is vectorized, and the `count += 1.3` code is not vectorized. For whatever reason that vectorization is unsuccessful and the vectorized loop runs slower (at least on your machine and on my machine). Optimization is hard.

The Swift loop runs slower because Swift performs arithmetic overflow checks that C does not, and in this case swiftc was unable to optimize them all away.

If you use &+ instead of +, or compile with -Ounchecked, then Swift won't perform the overflow checks. Unfortunately in this case you then get the same slower vectorized code from swiftc as you did from clang's `count += 1` case; presumably both clang and swiftc get this pessimization from LLVM. I couldn't find a way to disable LLVM vectorization from swiftc.


-- 
Greg Parker     gparker at apple.com <mailto:gparker at apple.com>     Runtime Wrangler


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161012/5d00b6ce/attachment.html>


More information about the swift-users mailing list