Compare the performance of simple arithmetic operations in C#

[performance]

I saw a post the other day that said division was the slowest arithmetic operation so I wrote this example to see exactly how the performance of multiplication, division, addition, and subtraction differ with floating point numbers.

When you click the Go button, the program executes loops that test each of the operations. The following code shows how the program tests the performance of multiplication.

Stopwatch watch = new Stopwatch();
int num_trials = int.Parse(txtNumTrials.Text);
float x = 13, y, z;

y = 1 / 7f;
watch.Start();
for (int i = 0; i < num_trials; i++)
{
    z = x * y;
}
watch.Stop();
txtTimeMult.Text = watch.Elapsed.TotalSeconds.ToString("0.00") +
    " secs";

The other loops are similar. If you look closely at the picture, you’ll see that division is indeed the slowest of the four operations. Multiplication, addition, and subtraction all have roughly the same performance.

Note that all of the operations are extremely fast. Even division took only 3.41 seconds to perform 1 billion trials, so in most programs the difference in performance doesn’t matter much. If your program must perform a huge number of operations, however, you may gain a slight performance increase if you use multiplication instead of division. For example, instead of dividing by 4, you could multiply by 0.25.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in mathematics, performance and tagged , , , , , , , , , , , . Bookmark the permalink.

One Response to Compare the performance of simple arithmetic operations in C#

  1. szulak says:

    I have write nice article about caching object in C#. You can find it here: http://blog.szulak.net/programming/caching-objects-in-c/

Leave a Reply

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