See how much time a checked block takes in C#

example

The post Control overflow behavior with checked and unchecked in C# explains how to use checked blocks to watch for integer overflow. If you don’t use checked, the program may encounter integer overflow errors without you knowing it.

It seems crazy to have checked disabled by default, but there is a reason. Checking for integer overflow after every calculation takes some time so it slows the program down. This example measures how much time.

When you enter a number of trials and click Go, the following code executes.

private void btnGo_Click(object sender, EventArgs e)
{
    txtChecked.Clear();
    txtUnchecked.Clear();
    Cursor = Cursors.WaitCursor;
    Refresh();

    int num_trials = int.Parse(txtNumTrials.Text);
    Stopwatch watch = new Stopwatch();

    watch.Start();
    checked
    {
        for (int i = 0; i < num_trials; i++)
        {
            for (int j = 0; j < 1000; j++)
            {
                int k = i - j;
            }
        }
    }
    watch.Stop();
    txtChecked.Text =
        watch.Elapsed.TotalSeconds.ToString("0.00") +
        " seconds";
    txtChecked.Refresh();

    watch.Reset();
    watch.Start();
    unchecked
    {
        for (int i = 0; i < num_trials; i++)
        {
            for (int j = 0; j < 1000; j++)
            {
                int k = i - j;
            }
        }
    }
    watch.Stop();
    txtUnchecked.Text =
        watch.Elapsed.TotalSeconds.ToString("0.00") +
        " seconds";

    Cursor = Cursors.Default;
}

After some preliminaries, the program gets the number of trials and creates a Stopwatch. It starts the watch and performs the trials inside a checked block. For each trial, it performs an integer subtraction 1,000 times. When it finishes, the program displays the elapsed time.

The program then performs the trials again, this time in an unchecked block.

If you look closely at the picture above, you'll see that the checked block added significantly to the time used. That's why Microsoft made integer calculations unchecked by default: to save time. If you know your calculations cannot cause an overflow, you can perform them without overflow checking to save some time.

I still think that's a crazy default. It would be better to check calculations by default and disable checking only when you know there won't be a problem rather than disabling checking by default.


Download Example   Follow me on Twitter   RSS feed




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in calculations, mathematics, performance, syntax and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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