Benchmarking my Code

I joined last week and I’m a little addicted.  The coding challenges are a good motivation to learn new methods and techniques.

I’ve been working on this kata today.  The challenge states “props if you do it without a nested loop,”  so I tried a few different ways.  After a little noodling around, I decided on the strategy of creating an array of arrays, passing a block to which would insert the proper values as the array was created.  Then Array.reduce would sum it up for me neat and clean.

I had trouble coming up with the code to initialize the arrays though.  I tried { } but couldn’t figure out how to increment properly as I went along.  So I just started hacking away, keeping the original idea of creating an array of arrays, inserting the values, and then using reduce at the end.  Here is my first function that passed the tests:

with a loopAs you can see I ended up with a nested loop.  But the tests passed, so I hit submit!

Apparently there’s a cutoff time.  It took more than 6 seconds to complete the tests to pass submission.  So I tried benchmarking the code:

benchmarking benchmarks with a loopHoly crap!  Look at the jump in time.  I know enough about Big O to know this is not good.

So I simplified a little bit:

Screenshot from 2015-11-01 18:44:17No need to create all those arrays, so I just pulled them out.  The results, with the same parameters passed to Benchmark, were:

Benchmarking the sumMuch better.  But although it’s passing the first round of tests, it’s still not passing the 6 second cutoff time for the submit tests, so I’ll keep trying.

One thought on “Benchmarking my Code”

Leave a Reply

Your email address will not be published. Required fields are marked *