Compare the performance of simple arithmetic operations in C#

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

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

int num_trials = int.Parse(txtNumTrials.Text);
DateTime start_time, stop_time;
TimeSpan elapsed;
float x = 13, y, z;

y = 1 / 7f;
start_time = DateTime.Now;
for (int i = 0; i < num_trials; i++)
{
    z = x * y;
}
stop_time = DateTime.Now;
elapsed = stop_time - start_time;
txtTimeMult.Text = elapsed.TotalSeconds.ToString("0.00") + " secs";
txtTimeMult.Refresh();

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 fast. Even division took only 1.76 seconds to perform 100 million trials so in most programs the difference in speed 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.