Loading

Bits & Bytes

Posts Tagged ‘time’

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 Timer Events in C#

If you want something to happen in a C# program at regular time intervals, the ideal way is to create a callback function that makes use of the Timer class. Below, I have created a class called CTimedObject that holds a Timer object. In the constructor, the Timer is allocated with a time interval of 2000 milliseconds or 2 seconds. Then OnTimedEvent() is set as a callback using the += operator and the Elapsed property. Finally, The Timer is started via a call to Start().

At this point, OnTimedEvent() will be called every 2 seconds. Inside the OnTimedEvent() function, the time is written to the console window via the passed in event object of type ElapsedEventArgs. The Object that is passed in is the Timer. Executing the program, the output looks like this

TimerEvent

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            CTimedObject qTimedObject = new CTimedObject();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }
    }
}

CTimedObject.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            Timer qTimer = new Timer(2000);
            qTimer.Elapsed += OnTimedEvent;
            qTimer.Start();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }

        static private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

The code above demonstrates how to use a Timer in an object. Alternatively, we could do the same thing more simply if we just want the event to fire with a static function. Below, we have code that does exacly the same thing without using a separate class.

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    public class CTimedObject {

        Timer mqTimer = null;

        public CTimedObject() {
            mqTimer = new Timer(2000);
            mqTimer.Elapsed += OnTimedEvent;
            mqTimer.Start();
        }

        private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

Generating Sounds in Actionscript 3.0

This program shows how to generate and play a sound. The generated sound is in the form of a sine wave, and it plays whenever the screen is clicked. Left-click the box above to hear the sound play.

The entire code to generate the sound is shown below. The first three lines just output the message “Click To Play.” The next two lines create a Sound object and an integer for the time. The two lines after that set callbacks for generating sound and responding to mouse clicks.

The rest of the program consists of the PlaySound() and Generator() functions. The PlaySound() function initializes the integer that keeps track of the sample time to 0 and then calls play() on the Sound object. The Generator() function writes 8192 samples at a time for the left and right channels; the generated sound is a sine wave that lasts half of a second, since sounds have 44100 samples per second.

// Output the initial instructions to user
var qInstructions:TextField = new TextField();
qInstructions.text = "Click To Play";
addChild(qInstructions);

var qSound:Sound = new Sound();
var iTime:int = 0;

qSound.addEventListener(SampleDataEvent.SAMPLE_DATA, Generator);
stage.addEventListener(MouseEvent.CLICK, PlaySound);

function PlaySound(e:Event):void {
	iTime = 0;
	qSound.play();
}

function Generator(event:SampleDataEvent):void {
	for (var i:int = 0; i < 8192; ++i) {
		// Play for half of a second
		if (iTime >= 22050) {
			return;
		}
		event.data.writeFloat(Math.sin(iTime/25));
		event.data.writeFloat(Math.cos(iTime/25));
		++iTime;
	}
}