[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Compare the performance of simple arithmetic operations in C#

[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 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.