Hacker News new | past | comments | ask | show | jobs | submit login
A Very Simple Genetic Algorithm Written in Swift 3 (gist.github.com)
105 points by brothrock on Nov 11, 2016 | hide | past | favorite | 36 comments



> let POP_SIZE = 50

c'mon everyone knows genetic population is 30

(I kid I kid but that number has an interesting story https://statswithcats.wordpress.com/2010/07/11/30-samples-st... )


It's not the population size, but the number of times you run the evolutionary algorithm with different seeds.


> Note -- this is much slower than the python version

Surprising. Swift, a compiled, static language, is slower than python in this use case?


Yeah. Swift is unique in that it features both incredibly slow compile times (in the good case, in bad cases it can abort due to timeouts on one line, 40 character expressions) AND slow runtime speed, especially when not optimising.

Code without the optimiser can easily be several hundred to more than a thousand times slower than optimised code. And of course the optimiser makes compile times even slower.

It's really quite a spectacle.


This is just speculation, but slowness might be because this is being run as a script via /usr/bin/swift, rather than being precompiled into a binary.

Certainly I have found my own Swift scripts seem to be a lot slower than compiled programs.

EDIT: from my own test with 1000 iterations, script version 17s, compiled version (release build) 5.4s


ah great point. I'll time it both ways and see where I'm at.


I compiled it down and did a quick profile. Looks like a lot of the time is spent on line 96, converting a Character to its ascii value.

https://dl.dropboxusercontent.com/u/13740348/Screen%20Shot%2...


That's because Character is very, very different from ASCII in Swift (a character in Swift holds an extended grapheme cluster. See https://developer.apple.com/reference/swift/character). I also doubt the way they compute its ASCII value is optimal:

  extension Character {
    var asciiValue: UInt32? {
        return  String(self)
            .unicodeScalars
            .filter{$0.isASCII}
            .first?
            .value
    }
  }
Certainly if it is optimal, but probably also if it isn't, I would change the program to not do that conversion in inner loops.


This is awesome guys. Thanks.



good stuff. tbh though, only ~3x slowdown in scripting imo is pretty damn good 8)


Isn't the "scripting" part just automatically compiling behind the scenes before running? It's not an interpreter or a VM. So the code runs just as fast as the compiled version, it's just that you pay a startup cost.


That's true between a debug build and just running it as a script I believe. But a release version will be optimized, I imagine if they compared a debug build to the scripted version they'd perform similarly.


Can confirm, Debug build runs in similar time to script.


Difference is that Release builds do whole-module optimization in Swift 3.

That allows for more aggressive code specialization and inlining and can remove more reference count updates (https://swift.org/blog/whole-module-optimizations/)


however for comparison, presented without comment: python version 0.708s


btw was this after compiled to pyc?


Not sure, I'm not seeing a .pyc file in the directory. Same every time I run it though.


My guess it is all of the string converting back and forth to character arrays.


Yep, replaced string with Int array and now it is much faster.

https://gist.github.com/rookie/3d9a848c6fefacc4254da921da79b...

It now runs faster (when compiled, optimized) than the python code.

    xcrun -sdk macosx swiftc -O gen.swift


Ooh yeah, 0m0.363s for 1000 iterations on mine. So the slowness was in the string manipulation and character conversion operations.


I've learned from years of working on making code more performant that the biggest code smells to look at first are string operations.


stuff like this can't help

var n = Double(arc4random_uniform(UInt32(weightTotal * 1000000.0))) / 1000000.0


Yep totally, going to take another pass to try and make it faster. This was just a make it work experiment. Had a few fun troubles with random, but at the moment it just crawls :(.


Out of curiosity, what's wrong with that line? Why is it slow?


starting from inside the arc4random call you have double float multiplication, then cast to uint32, then the arc4rand call, then the double cast for the uint32 result and then a double float division. this adds up in instructions.


Did not expect to see "cfdrake" when I initially clicked the link - nice port! :)

Agreed with e28eta - I actually saw RubikSwift demoed at Swift Summit a few days ago as well and enjoyed it. Definitely check it out if you're interested in the topic.


I thought this was going to be a link to [1], from a talk given at Swift Summit a couple days ago. I haven't really looked at the code for either one to compare them, but for people who are interested, here's a second simple genetic algorithm in Swift (found in RubikSwift/GeneticsSolver.swift)

https://github.com/JaviSoto/RubikSwift


Swift looks a lot like Typescript. This is the first time I've read swift code and I'm taken by surprise by its elegance.

I'm gonna give it a shot


swift is a fantastic language, but it's absolutely not as mature as other language you're probably used to. In particular, you may experience a lot of compiler crash, typing bugs, and very bad compile time.

But i'm 100% certain it's going to be one of the most used language server side in the coming years.


Here's a little Swift Cookbook to get more of a flavor:

http://www.h4labs.com/dev/ios/swift_cookbook.html


The other languages are here: https://github.com/jsvazic/GAHelloWorld


[flagged]


I wanted an example of a simple genetic algorithm in swift, couldn't find it so I wrote it from something I found in python. 0% special, but thought i'd share. Take it or leave it, dude.


Just to add to this, if you don't like it, don't click on it/comment on it. The front page algorithm put this item here because people upvoted it, not because it queried a random selection of the user base and asked if it was "worthy".


Shouldn't people should feel free to share whatever they want that's HN material?

That's why we vote articles up. Sometimes the comments alone in a basic post add a lot of value.


Agreed. And voting the whole thing up.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: