EN
C# / .NET - get current machine time in milliseconds
8 points
C# / .NET it is possible to take machine time in milliseconds in following way.
xxxxxxxxxx
1
public static class TimeUtils
2
{
3
public static long GetMilliseconds()
4
{
5
double timestamp = Stopwatch.GetTimestamp();
6
double milliseconds = 1_000.0 * timestamp / Stopwatch.Frequency;
7
8
return (long)milliseconds;
9
}
10
}
Example:
xxxxxxxxxx
1
long t1 = TimeUtils.GetMilliseconds();
2
3
Thread.Sleep(1000);
4
5
long t2 = TimeUtils.GetMilliseconds();
6
long dt = t2 - t1;
7
8
Console.WriteLine(t2 + " - " + t1 + " = " + dt + " ms");
Output:
xxxxxxxxxx
1
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.