Languages
[Edit]
EN

C# / .NET - get current machine time in milliseconds

8 points
Created by:
Kate_C
2854

C# / .NET it is possible to take machine time in milliseconds in following way.

Getting milli time with Stopwatch.GetTimestamp method example

public static class TimeUtils
{
	public static long GetMilliseconds()
	{
		double timestamp = Stopwatch.GetTimestamp();
		double milliseconds = 1_000.0 * timestamp / Stopwatch.Frequency;

		return (long)milliseconds;
	}
}

Example:

long t1 = TimeUtils.GetMilliseconds();

Thread.Sleep(1000);

long t2 = TimeUtils.GetMilliseconds();
long dt = t2 - t1;

Console.WriteLine(t2 + " - " + t1 + " = " + dt + " ms");

Output:

197778624 - 197777623 = 1001 ms
Notes: 
  • Stopwatch.GetTimestamp returns time from timer mechanism - system up time.
  • The best application of this time could be measuring how much time took some operations.

References

  1. Stopwatch.GetTimestamp Method - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.