Jump to content
  • Advertisement
Sign in to follow this  
Ksingh30

C# time(miliseconds)

This topic is 4149 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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();

Share this post


Link to post
Share on other sites
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;
}
}
}



Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!