0

I have written a function to calculate a formula in C# that uses nested for loops. It runs slower than I would like and I have been trying to speed it up. Is there a good way to determine if my code can optimized further in C# or if I need to move to a language that is machine compiled such as C++?

I know each case will be different but is there a general process/checklist that could be used to determine if more optimization is possible?

Fr33dan
  • 4,227
  • 3
  • 35
  • 62
  • 1
    Thanks to the JITter, raw computations are not likely to be faster in C++. (unless you are an _extremely_ skilled C++ developer) – SLaks May 30 '14 at 02:23
  • You have remembered to build for Release, not Debug? Other than that my only suggestion is that you run your program under a debugger that will show the actual machine instructions (not the .NET intermediate language), and see if you can see any obvious inefficiencies. If not, then there isn't much you can do. (This assumes you have a bit of knowledge about machine instructions) – RenniePet May 30 '14 at 02:29
  • @RenniePet Yes I have used the release option, it is not any faster in my case than the debug option (which I found strange). I had a class on machine instructions in school but I do not think I have enough knowledge for that type of analysis to yield useful results. – Fr33dan May 30 '14 at 02:32
  • @slaks (really?)[http://benchmarksgame.alioth.debian.org/] -- generally, jitted languages are noticably slower when apples are compared with apples on pretty raw computation problems. – Yakk - Adam Nevraumont May 30 '14 at 02:40
  • @Yakk brackets, then parentheses. you know this :p – keyser May 30 '14 at 02:41
  • I'm a bit surprised about your statement that Debug and Release builds have the same performance. See here http://stackoverflow.com/questions/4043821/performance-differences-between-debug-and-release-builds Are you 100% sure your Release builds are Release builds? http://stevesmithblog.com/blog/determine-whether-an-assembly-was-compiled-in-debug-mode/ – RenniePet May 30 '14 at 02:46
  • @RenniePet I used the code mentioned to make sure. If there is any improvement it is within the variability of the run time of the code. (which is my case on my sample data set varies between 1.66 to 1.69 seconds). – Fr33dan May 30 '14 at 03:08

1 Answers1

3

No, there is no general rule that works for any algorithm saying "This algorithm cannot be optimized further". If such a tool existed, it would be applied to, well, any existing program.

However a profiler can show you hot spots in your code that should be optimized : it is usually a good idea to run a profiler on time-sensitive parts of the program showing inefficiencies.

Compiling with .NET native could give you results closer to what one would expect to the equivalent C++ program.

quantdev
  • 23,517
  • 5
  • 55
  • 88