C # code size and code execution time

Is there a way to find the size of the code and what is its runtime to compare the two codes and decide which is better?

For example, let's say I want to find the size and runtime of this

Code 1

for(int i=0; i<5; i++) { sum+=1; } 

and this one

Code 2

 for(int i=0; i<=4; i++) { sum = sum + 1; } 

to decide which is better (now I don't need this example). For example, the result would be:

 Code 1: Size: ? KB Time: ? ms Code 2: Size: ? KB Time: ? ms 
+7
source share
3 answers

You can use ANTS Profiler http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/ (a paid product, but they have a trial version) or some other Profiler product (ANTS, vTune, OptimizeIt, DevPartner, YourKit, dotTrace) on the market.

You can also implement the functions yourself by installing some unit tests that perform these 2 functions using the StopWatch hand tools to compare runtime (faster and cheaper). Unit tests will also ensure that you do not have any performance regressions if you need to change the implementation later. http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

  var stopWatch = new Stopwatch(); stopWatch.Start(); var result = CallFunction(); stopWatch.Stop(); var executionTime = stopWatch.Elapsed; 
+15
source

To measure the runtime, you must use StopWatch - you will need to run several iterations several times and align them if you want a proper benchmark.

 var sw = new StopWatch(); sw.Start(); // do a million iterations sw.Stop(); var time = sw.Elapsed; 

As for memory sizes - you can use one of many memory profiles - ANTS PROFESSIONAL PROFILE , dotTrace - these are two commercial options.

+3
source

You can use the FileInfo class (see the Length property) to determine the file size.

You can use the Stopwatch class to determine how long it takes to run the program.

+2
source

All Articles