{"id":723,"date":"2009-03-01T16:46:22","date_gmt":"2009-03-01T21:46:22","guid":{"rendered":"http:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/723"},"modified":"2010-04-29T15:01:28","modified_gmt":"2010-04-29T20:01:28","slug":"silverlight-stopwatch-class-in-c","status":"publish","type":"post","link":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/723","title":{"rendered":"Silverlight Stopwatch class in C#"},"content":{"rendered":"

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.<\/p>\n

Just create an instance of the class and call Start<\/strong> to start the timer, and then get the value of one of the\u00a0 ElapsedNNN <\/em><\/strong>properties to get a live reading without stopping the timer or the Stop<\/strong> function to stop the timer completely.<\/p>\n

Update April 4, 2010:<\/strong><\/p>\n

Even though there were some doubters in the comments suggesting I didn\u2019t test the original version that was here \u2013 I had \u2026 so I\u2019m confused as to why it had worked for me, yet not in current versions of Silverlight. In any case, I\u2019ve updated the code and have included a sample of how to use it. Thanks to those who provided suggested fixes.<\/p>\n

using <\/span>System;\r\nusing <\/span>System.Diagnostics;\r\n\r\nnamespace <\/span>WiredPrairie.Silverlight\r\n{\r\n    \/\/\/ <summary>\r\n    \/\/\/ <\/span>Stopwatch is used to measure the general performance of Silverlight functionality. Silverlight\r\n    <\/span>\/\/\/ <\/span>does not currently provide a high resolution timer as is available in many operating systems,\r\n    <\/span>\/\/\/ <\/span>so the resolution of this timer is limited to milliseconds. This class is best used to measure\r\n    <\/span>\/\/\/ <\/span>the relative performance of functions over many iterations.\r\n    <\/span>\/\/\/ <\/summary>\r\n    <\/span>public sealed class <\/span>Stopwatch\r\n    <\/span>{\r\n        private long <\/span>_startTick;\r\n        private long <\/span>_elapsed;\r\n        private bool <\/span>_isRunning;\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Creates a new instance of the class and starts the watch immediately.\r\n        <\/span>\/\/\/ <\/summary>\r\n        \/\/\/ <returns><\/span>An instance of Stopwatch, running.<\/span><\/returns>\r\n        <\/span>public static <\/span>Stopwatch <\/span>StartNew()\r\n        {\r\n            Stopwatch <\/span>sw = new <\/span>Stopwatch<\/span>();\r\n            sw.Start();\r\n            return <\/span>sw;\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Creates an instance of the Stopwatch class.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public <\/span>Stopwatch() { }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Completely resets and deactivates the timer.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public void <\/span>Reset()\r\n        {\r\n            _elapsed = 0;\r\n            _isRunning = false<\/span>;\r\n            _startTick = 0;\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Begins the timer.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public void <\/span>Start()\r\n        {\r\n            if <\/span>(!_isRunning)\r\n            {\r\n                _startTick = GetCurrentTicks();\r\n                _isRunning = true<\/span>;\r\n            }\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Stops the current timer.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public void <\/span>Stop()\r\n        {\r\n            if <\/span>(_isRunning)\r\n            {\r\n                _elapsed += GetCurrentTicks() - _startTick;\r\n                _isRunning = false<\/span>;\r\n            }\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Gets a value indicating whether the instance is currently recording.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public bool <\/span>IsRunning\r\n        {\r\n            get <\/span>{ return <\/span>_isRunning; }\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Gets the Elapsed time as a Timespan.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public <\/span>TimeSpan <\/span>Elapsed\r\n        {\r\n            get <\/span>{ return <\/span>TimeSpan<\/span>.FromMilliseconds(ElapsedMilliseconds); }\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Gets the Elapsed time as the total number of milliseconds.\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public long <\/span>ElapsedMilliseconds\r\n        {\r\n            get <\/span>{ return <\/span>GetCurrentElapsedTicks() \/ TimeSpan<\/span>.TicksPerMillisecond; }\r\n        }\r\n\r\n        \/\/\/ <summary>\r\n        \/\/\/ <\/span>Gets the Elapsed time as the total number of ticks (which is faked\r\n        <\/span>\/\/\/ <\/span>as Silverlight doesn't have a way to get at the actual \"Ticks\")\r\n        <\/span>\/\/\/ <\/summary>\r\n        <\/span>public long <\/span>ElapsedTicks\r\n        {\r\n            get <\/span>{ return <\/span>GetCurrentElapsedTicks(); }\r\n        }\r\n\r\n        private long <\/span>GetCurrentElapsedTicks()\r\n        {\r\n            return <\/span>(long<\/span>) (this<\/span>._elapsed + (IsRunning ? (GetCurrentTicks() - _startTick) : 0));\r\n        }\r\n\r\n        private long <\/span>GetCurrentTicks()\r\n        {\r\n            \/\/ TickCount: Gets the number of milliseconds elapsed since the system started.\r\n            <\/span>return <\/span>Environment<\/span>.TickCount * TimeSpan<\/span>.TicksPerMillisecond;\r\n        }\r\n    }\r\n}<\/pre>\n

<\/a>
\nSample usage:<\/p>\n

Stopwatch <\/span>sw1 = Stopwatch<\/span>.StartNew();\r\nThread<\/span>.Sleep(20);\r\nsw1.Stop();\r\nDebug<\/span>.WriteLine(\"Slept for 5 milliseconds ... actually: {0}\"<\/span>, sw1.ElapsedMilliseconds);<\/pre>\n

<\/a><\/a><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"

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 […]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[4,14],"tags":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pd5QIe-bF","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":1030,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1030","url_meta":{"origin":723,"position":0},"title":"Silverlight Stopwatch Class, Part 2","date":"April 2, 2010","format":false,"excerpt":"I recently made a fix to a Silverlight stopwatch class I wrote last year. In doing so, I decided to kick it up a notch. using (new StopwatchPlus(\"Constructor\")) { \/\/Debug.WriteLine(\"Initialized: Ellapsed Ticks: {0}, Ellapsed Milliseconds: {1}\", sw.EllapsedTicks, sw.EllapsedMilliseconds); InitializeComponent(); Thread.Sleep(600); } Instead of just a simple Stopwatch class, I added\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":426,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/426","url_meta":{"origin":723,"position":1},"title":"Visual WebGUI — Uh? Neat technology for someone else.","date":"July 16, 2008","format":false,"excerpt":"At the top of the page linked above, you can try the Ajax version or the Silverlight version of their web-mail demo. Try it. I won't say that I'm not impressed by what they've accomplished technically. It's impressive. They use a WinForms designer to build parts of the user interface\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"image","src":"https:\/\/i0.wp.com\/www.wiredprairie.us\/blog\/wp-content\/uploads\/2008\/07\/image-thumb2.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":568,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/568","url_meta":{"origin":723,"position":2},"title":"Data Binding and Tooltips in Silverlight","date":"September 19, 2008","format":false,"excerpt":"Have you ever wanted to databind a tooltip in Silverlight (or WPF for that matter), and found that the DataContext isn't available for tooltips (the datacontext is null)? It's very annoying. Tooltips, unfortunately, aren't connected to their parents in anyway when they're created, so they loose the ability to connect\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":388,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/388","url_meta":{"origin":723,"position":3},"title":"Silverlight Weather Demonstration","date":"June 26, 2008","format":false,"excerpt":"Demonstration available here. (You'll need to wait for a moment while it loads the first time). I've created a reasonably simple, yet multi-technology (and discipline) demonstration using Silverlight for the user interface and ASP.NET as the back-end. The demonstration uses: Silverlight 2.0 Data binding Delayed downloading of images \"Web services\"\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.wiredprairie.us\/blog\/wp-content\/uploads\/2008\/06\/image21.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":394,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/394","url_meta":{"origin":723,"position":4},"title":"Some Simple Silverlight 2.0 Particles, with sticky tape ….","date":"June 29, 2008","format":false,"excerpt":"Live demo here. There are a few demos of using the HTML Canvas element floating around the web (which exists natively in WebKit, Firefox, and Opera and as a custom class using excanvas for Internet Explorer). I was inspired to clone the particle demo using Silverlight (and add a silly\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"image","src":"https:\/\/i0.wp.com\/www.wiredprairie.us\/blog\/wp-content\/uploads\/2008\/06\/image26.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":1162,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1162","url_meta":{"origin":723,"position":5},"title":"Silverlight to become Microsoft’s next VB6?","date":"November 1, 2010","format":false,"excerpt":"There was a huge uproar in the tech blogs this past week regarding some comments made by Bob Muglia (of Microsoft) as reported by Mary Joe Foley in a post entitled, \u201cMicrosoft: Our Strategy with Silverlight has shifted.\u201d The quotes that caused the most ruckus are: \u201cSilverlight is our development\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/posts\/723"}],"collection":[{"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/comments?post=723"}],"version-history":[{"count":4,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/posts\/723\/revisions"}],"predecessor-version":[{"id":804,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/posts\/723\/revisions\/804"}],"wp:attachment":[{"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/media?parent=723"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/categories?post=723"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wiredprairie.us\/blog\/index.php\/wpjson\/wp\/v2\/tags?post=723"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}