Silverlight Stopwatch class in C#

I needed a simple method for doing some timings in Silverlight. Silverlight lacks the high performance query counter that is available natively in Windows (and available in .NET 3.5 for example), but it does have a TickCount. My code (mostly) mirrors the existing .NET Stopwatch class using the TickCount property of the Environment class.

Just create an instance of the class and call Start to start the timer, and then get the value of one of the  ElapsedNNN properties to get a live reading without stopping the timer or the Stop function to stop the timer completely.

Update April 4, 2010:

Even though there were some doubters in the comments suggesting I didn’t test the original version that was here – I had … so I’m confused as to why it had worked for me, yet not in current versions of Silverlight. In any case, I’ve updated the code and have included a sample of how to use it. Thanks to those who provided suggested fixes.

using System;
using System.Diagnostics;

namespace WiredPrairie.Silverlight
{
    /// <summary>
    /// Stopwatch is used to measure the general performance of Silverlight functionality. Silverlight
    /// does not currently provide a high resolution timer as is available in many operating systems,
    /// so the resolution of this timer is limited to milliseconds. This class is best used to measure
    /// the relative performance of functions over many iterations.
    /// </summary>
    public sealed class Stopwatch
    {
        private long _startTick;
        private long _elapsed;
        private bool _isRunning;

        /// <summary>
        /// Creates a new instance of the class and starts the watch immediately.
        /// </summary>
        /// <returns>An instance of Stopwatch, running.</returns>
        public static Stopwatch StartNew()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            return sw;
        }

        /// <summary>
        /// Creates an instance of the Stopwatch class.
        /// </summary>
        public Stopwatch() { }

        /// <summary>
        /// Completely resets and deactivates the timer.
        /// </summary>
        public void Reset()
        {
            _elapsed = 0;
            _isRunning = false;
            _startTick = 0;
        }

        /// <summary>
        /// Begins the timer.
        /// </summary>
        public void Start()
        {
            if (!_isRunning)
            {
                _startTick = GetCurrentTicks();
                _isRunning = true;
            }
        }

        /// <summary>
        /// Stops the current timer.
        /// </summary>
        public void Stop()
        {
            if (_isRunning)
            {
                _elapsed += GetCurrentTicks() - _startTick;
                _isRunning = false;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the instance is currently recording.
        /// </summary>
        public bool IsRunning
        {
            get { return _isRunning; }
        }

        /// <summary>
        /// Gets the Elapsed time as a Timespan.
        /// </summary>
        public TimeSpan Elapsed
        {
            get { return TimeSpan.FromMilliseconds(ElapsedMilliseconds); }
        }

        /// <summary>
        /// Gets the Elapsed time as the total number of milliseconds.
        /// </summary>
        public long ElapsedMilliseconds
        {
            get { return GetCurrentElapsedTicks() / TimeSpan.TicksPerMillisecond; }
        }

        /// <summary>
        /// Gets the Elapsed time as the total number of ticks (which is faked
        /// as Silverlight doesn't have a way to get at the actual "Ticks")
        /// </summary>
        public long ElapsedTicks
        {
            get { return GetCurrentElapsedTicks(); }
        }

        private long GetCurrentElapsedTicks()
        {
            return (long) (this._elapsed + (IsRunning ? (GetCurrentTicks() - _startTick) : 0));
        }

        private long GetCurrentTicks()
        {
            // TickCount: Gets the number of milliseconds elapsed since the system started.
            return Environment.TickCount * TimeSpan.TicksPerMillisecond;
        }
    }
}


Sample usage:

Stopwatch sw1 = Stopwatch.StartNew();
Thread.Sleep(20);
sw1.Stop();
Debug.WriteLine("Slept for 5 milliseconds ... actually: {0}", sw1.ElapsedMilliseconds);

Why write your own rendering engine anymore?

I just installed and ran the latest version of Lavasoft’s Ad-aware Free (Anniversary Edition) and was disappointed by the general fuzziness of the text.

image

So, I grabbed one of my favorite tools, Spy++ to do a little bit of technology spelunking. The interesting thing was that there was only a single window in use:

image

The fuzziness of the text initially made me think GDIPlus, but a quick scan using Depends seemed to indicate that wasn’t the case:image

The text rendering just isn’t right:

image

For example, check out the kerning of the “e” and the “m” above.  I tried the same text in Photoshop (wondering if it was a bitmap from a common image generation tool):

image

But, it looks fine in every aliasing option.

It wasn’t GDI, or GDI+:

image 

And not WPF:

image

There are probably a handful of toolkits that it could be, but I don’t have the patience to try a match anymore.

I’m just not sure why they’d take the time to not use a standard Windows provided text / graphics engine? I’m not opposed to an architecture that minimizes HWND usage to increase efficiency or allow for some unique user experiences (like skinning), but why go this far? What’s the gain? When the quality of text isn’t near perfect, why wouldn’t you abandon the technique? Anyone know?

Usability Mistakes in Web Design

From Smashing Magazine: 9 Common Usability Mistakes in Web Design.

Some great tips.

For #1, I definitely appreciate web sites that use actual decent clickable areas for page navigation. These aren’t too bad for example (from MSDN):

image

But there’s still too many web sites like this:

1 2 3 4 5 6 7 8 9 10 … 31 32

The clickable area for each page is no wider than the width of the character! Don’t forget that not everyone has the mouse dexterity of a 14 year-old avid game player! :)

5 Great Online Color Palette selection and design tools

Can’t find the color that matches your favorite cyan? Use one of these web based color palette selection tools to help you find the perfect match!  My current favorites are the first two, Color Scheme Designer and Kuler.

Color Scheme Designer

Easy to use and has a simulation of what some people may see who have various color vision deficiencies.

image

 

Kuler

A slick Adobe Flash based color selection and sharing site.

image

ColorJack

Although not as easy to use right away, a very powerful color selection tool with many different features.

image

Color Wizard

Although the actual selection of color isn’t as much fun as some of the other online options, the Color Wizard has lots of onscreen colors at one time for easy identification of options without a lot of fuss. (The worst part is that the page is heavily loaded with advertisements).

image

 

Sessions Color Wheel Color Calculator

The link to this is actually mid-way down the middle of the page. This is a another nice interactive color selection tool. I would have prefered that they hadn’t picked an orange/gold color as the base color for their selection application.

image

And a bonus,

SitePro Central’s Colour Scheme Chooser

Simple and efficient.

image