Bits & Bytes

Posts Tagged ‘simple’

Using the C# StopWatch Class to Time Code

In order to optimize C# code, you need to be able to time sections of it to determine what is causing performance problems. The built-in Stopwatch class offers a simple solution for doing this.

The short program below demonstrates a simple example usage of the Stopwatch class. First, we create a new Stopwatch object. Then we call Start() to begin counting the time. The next section is a loop with nothing in it that runs a 1 billion times; this represents something that we would like to time. At the end of the loop, we call Stop() to record the elapsed time. Finally, we output the time at the end.

The program takes approximately 2 and a half seconds to run through the loop 1 billion times. The loop actually takes some time because it must increment the integer i and check whether it is less than 1 billion. After 1 billion times, this adds up to just a few seconds on my computer. Executing the program, yields a result like this.

StopwatchOutput

Program.cs

using System;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch qStopwatch = new Stopwatch();
        qStopwatch.Start();
        // This loop represents something that we want to time
        for (int i = 0; i < 1000000000; ++i) {
            // There is nothing here . . .
        }
        qStopwatch.Stop();

        Console.WriteLine("Elapsed Time " + qStopwatch.Elapsed);
    }
}

Creating a Simple Form to Display Text Messages in C#

Although it is possible to use a simple MessageBox for printing messages, it is sometimes convenient to use a window that you have more control over. Below, I have the C# code for a simple console application named “MyConsoleApplication.” I created the project using the Console Application template, which creates the empty Main() function shown below. The code file is named “Program.cs” for simplicity, but it could be named anything.

We need to add a reference to the assembly System.Windows.Forms, in order to be able create Forms in the code. We also need to add the corresponding using directive using System.Windows.Forms; at the top of the code file. Finally, we need to add a reference to the assembly System.Drawing in order to set the size of the Form in the line: qMyForm.ClientSize = qMyTextbox.Size;.

Beyond that, the code that I have added is all inside the Main() function. First, I create a Form and add the text “An Important Message” to the title bar. Next, I create a TextBox and set its size to 400 by 300 pixels. Then I set it to accept multiple lines of text, enable the vertical scrollbar to accommodate text overruns, and set it to be read only so that the text cannot be modified.

The middle block of code consists of several calls to the member function AppendText(). Each call adds a line of text from the Bible, Proverbs 4:10-13. The character sequence \u000D\u000A is the unicode representation of the carriage return and linefeed characters. So, that moves the text to the beginning of the next line. On a related note, the TextBox has word wrap enabled by default.

The third block of code sets the size of the containing Form to have a client area that is the same size as the TextBox. Then the TextBox is added to the Form, and the Form is displayed via a call to ShowDialog().

The output of the program looks like this:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FormStringOutput;
using System.Windows.Forms;

namespace MyConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Form qMyForm = new Form();
            // Sets the title bar text
            qMyForm.Text = "An Important Message";
            TextBox qMyTextbox = new TextBox();
            qMyTextbox.SetBounds(0, 0, 400, 300);
            qMyTextbox.Multiline = true;
            qMyTextbox.ScrollBars = ScrollBars.Vertical;
            qMyTextbox.ReadOnly = true;

            // Add messages via AppendText, using '\u000D\u000A' for new line characters
            qMyTextbox.AppendText("Hear, my child, and accept my words,\u000D\u000A");
            qMyTextbox.AppendText("    that the years of your life may be many.\u000D\u000A");
            qMyTextbox.AppendText("I have taught you the way of wisdom;\u000D\u000A");
            qMyTextbox.AppendText("    I have led you in the paths of uprightness.\u000D\u000A");
            qMyTextbox.AppendText("When you walk, your step will not be hampered;\u000D\u000A");
            qMyTextbox.AppendText("    and if you run, you will not stumble.\u000D\u000A");
            qMyTextbox.AppendText("Keep hold of instruction; do not let go;\u000D\u000A");
            qMyTextbox.AppendText("    guard her, for she is your life.\u000D\u000A");
            qMyTextbox.AppendText("\u000D\u000A             Proverbs 4:10-13\u000D\u000A");

            // Set the client area of the form equal to the size of the Text Box
            qMyForm.ClientSize = qMyTextbox.Size;
            // Add the Textbox to the form
            qMyForm.Controls.Add(qMyTextbox);
            // Display the form
            qMyForm.ShowDialog();
        }
    }
}

Creating a Simple Javascript Animation Using Recursion

The animation that we create in this example is a simple progress bar. Above, you can see a light gray rectangle with a darker gray rectangle inside it. The darker gray bar is the progress bar that moves from left to right across the screen.

The code for this animation is below. You can copy code into an empty file with a .html extension or just download the HTML file using this link. Just right-click that link and left-click “Save Link As…” and select a location to save it to. Then double-click the file to open it with a browser.

As you can see in the code below, we define two styles: animbkgd and animbar. These are used to create div elements for the background and the progress bar, respectively. The div elements are created inside the body tag near the bottom of the file.

At the bottom of the head section, we have script tags to define the Javascript code section. We begin by defining three variables: qpBkdg, qpBar, and iWidth. The first two are used to refer to background and progress bar div sections and are set inside the Initialize() function. The third variable keeps track of the width of the progress bar.

The animation is started after the page is loaded with code

window.onload = Initialize;

that sets the Initialize() function to be the callback function for when the page loads.

When Initialize() is called, is initializes the two variables and then calls the animation loop function Loop(). The Loop() function updates the width variables and then sets itself to be called again in 20 milliseconds. That is the effect of the call

setTimeout(Loop,20);

The setTimeout() function calls a function after a specified period of time. Here, it is set to call Loop() after 20 milliseconds. So, the code creates a recursive loop where Loop() is called every 20 milliseconds to create the animation.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>XoaX.net's Javascript Recusive Animation Example</title>

<style type="text/css">
#animbkgd {
    position:absolute;
    width: 480px;
    height: 50px;
    background:#aaaaaa;
    margin: 30px;
}

#animbar {
    position:absolute;
    width: 0px;
    height: 20px;
    background:#000000;
    left: 0px;
    top: 20px;
}
</style>

<script type="text/javascript">
/*<![CDATA[*/
var qpBkdg = null;
var qpBar = null;
var iWidth = 0;

function Loop() {
    qpBar.style.width = iWidth+'px';
    iWidth = ((iWidth + 1) % 480);
    setTimeout(Loop,20);
}

function Initialize() {
    qpBkdg = document.getElementById('animbkgd');
    qpBar = document.getElementById('animbar');
    Loop();
}

window.onload = Initialize;
/*]]>*/
</script>
</head>

<body>

<div id="animbkgd">
    <div id="animbar">
    </div>
</div>

</body>
</html>

 

© 2007–2024 XoaX.net LLC. All rights reserved.