Title: Compare speeds of arithmetic operations in C#
This example compares the speeds of arithmetic operations with different data types. There's a big difference between the speeds of operations using the decimal data type and the other types, so performing a loop a certain number of time is difficult. If the loop takes a reasonable amount of time for an int, then it takes too long for a decimal. Conversely if the loop takes a reasonable amount of time for a decimal, then it is too quick to get much of a measurement for the other data types.
This example takes a different approach so the measurements reasonable take a reasonable amount of time. It lets you enter a length of time and then it tests operations for that amount of time for each of the data types.
The following code shows how the program tests the decimal data type.
double sec_per_test = double.Parse(txtSecPerTest.Text);
DateTime start_time, stop_time, time_now;
TimeSpan elapsed;
double trials_per_sec, ns_per_trial;
...
// Decimal.
start_time = DateTime.Now;
stop_time = start_time.AddSeconds(sec_per_test);
for (int trial = 0; ; trial++)
{
decimal i = 12345m * 54231m / 13m;
decimal j = i * 267m;
i = j / 287m;
time_now = DateTime.Now;
if (time_now > stop_time)
{
elapsed = time_now  start_time;
trials_per_sec = trial / elapsed.TotalSeconds;
txtDecimal.Text = trials_per_sec.ToString("N");
txtDecimal.Refresh();
ns_per_trial = 1.0 / trials_per_sec * 1000000000;
txtDecimalSecs.Text = ns_per_trial.ToString("0.00000000");
txtDecimalSecs.Refresh();
break;
}
}
Before starting the tests, the program reads the number of seconds you entered. To test the decimal data type, it gets the current time and adds the desired length of the test to that to get the desired stop time.
The code then enters a loop that executes until the calculated stop time. Inside the loop the code performs some arithmetic operations. Then if the current time is after the desired stop time, the program displays the number of trials performed per second and the number of nanoseconds used by each of the arithmetic operations.
The code for the other data types is similar.
If you look at the results, you can see that the decimal is much slower than the others, taking almost three times as long. The other operators have comparable performance.
The moral is that you should generally use whichever data type makes the most sense. If performance is an issue, you might want to use double instead of decimal.
Download the example to experiment with it and to see additional details.
