C# time(miliseconds)

Started by
3 comments, last by TheUnbeliever 17 years, 2 months ago
I need to keep a counter of the number of miliseconds that have passed since the program first started running. everthing I have found so far is using this DateTime.Now.Millisecond but that gives me the miliseconds currently between 0-999.
Advertisement
You could look at the Stopwatch class (introduced in .NET 2)
You would have to start the timer during the your program init.

using System.Diagnostics

Stopwatch stop = new Stopwatch();

in your init code

Stopwatch.Start();

then when you need it...

long millisecondsnow = stop.ElapsedMilliseconds();

Another way is to use window's native high performance counter.

Here's a snippet of my own code. The value returned by "tick" is the number of seconds that have passed since it was last called. The value is more than precise enough to determine milliseconds as well.

using System;using System.Collections.Generic;using System.Text;using System.Security;using System.Runtime.InteropServices;namespace Facilis{    /// <summary>    /// Provides a Win32 implementation of the Timer abstract class.    /// </summary>    public class Win32Timer        : Timer    {        /// <summary>        /// Initialises a new instance of the Win32Timer class.        /// </summary>        public Win32Timer()        {            QueryPerformanceFrequency( ref this._frequency );            QueryPerformanceCounter( ref this._currentCount );        }        [DllImport( "kernel32" ), SuppressUnmanagedCodeSecurity]        private static extern bool QueryPerformanceFrequency( ref long PerformanceFrequency );        [DllImport( "kernel32" ), SuppressUnmanagedCodeSecurity]        private static extern bool QueryPerformanceCounter( ref long PerformanceCount );        private long _frequency = 0;        private long _currentCount = 0;        private double _deltatime = 0.0;        /// <summary>        /// Updates the timer.        /// </summary>        /// <returns></returns>        public override double Tick()        {            long lastcount = this._currentCount;            QueryPerformanceCounter( ref this._currentCount );            this._deltatime = (double)(this._currentCount - lastcount) / (double)this._frequency;            this.UpdateInterval( this._deltatime );            return this._deltatime;        }    }}
I think the Stopwatch class is probably just a nice wrapper for the performance counter anyway.
Store the value of System.Environment.TickCount on load then count from that?
[TheUnbeliever]

This topic is closed to new replies.

Advertisement