.net - Benchmarking small code samples in C#, can this implementation be improved? -


quite on find myself benchmarking small chunks of code see implemnetation fastest.

quite see comments benchmarking code not take account jitting or garbage collector.

i have following simple benchmarking function have evolved:

  static void profile(string description, int iterations, action func) {         // warm          func();         // clean         gc.collect();          var watch = new stopwatch();         watch.start();         (int = 0; < iterations; i++) {             func();         }         watch.stop();         console.write(description);         console.writeline(" time elapsed {0} ms", watch.elapsedmilliseconds);     } 

usage:

profile("a descriptions", how_many_iterations_to_run, () => {    // ... code being profiled }); 

does implementation have flaws? enough show implementaion x faster implementation y on z iterations? can think of ways improve this?

edit pretty clear time based approach (as opposed iterations), preferred, have implementations time checks not impact performance?

here modified function: recommended community, feel free amend community wiki.

static double profile(string description, int iterations, action func) {     //run @ highest priority minimize fluctuations caused other processes/threads     process.getcurrentprocess().priorityclass = processpriorityclass.high;     thread.currentthread.priority = threadpriority.highest;      // warm      func();      var watch = new stopwatch();       // clean     gc.collect();     gc.waitforpendingfinalizers();     gc.collect();      watch.start();     (int = 0; < iterations; i++) {         func();     }     watch.stop();     console.write(description);     console.writeline(" time elapsed {0} ms", watch.elapsed.totalmilliseconds);     return watch.elapsed.totalmilliseconds; } 

make sure compile in release optimizations enabled, , run tests outside of visual studio. last part important because jit stints optimizations debugger attached, in release mode.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -