How to display exact time for testing performance numbers in C #

I want to check the speed of the algorithm, what DateTimeoverload will give me the most accurate time? (I still need day / month / year / second, but then I also want milliseconds).

+3
source share
5 answers
+11
source

Stopwatch, . : , . ( Stopwatch, , .) , IO- , ( ) . , , ..

, , , , . , 5 ... .

- :

   [DllImport("kernel32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   static extern bool GetProcessTimes(IntPtr hProcess, 
      out FILETIME lpCreationTime, 
      out FILETIME lpExitTime,
      out ulong lpKernelTime,
      out ulong lpUserTime);

   static ulong GetTime(Process process)
   {
       FILETIME lpCreationTime, lpExitTime;
       ulong lpKernelTime, lpUserTime;

       GetProcessTimes(process.Handle, out lpCreationTime,
                       out lpExitTime, out lpKernelTime, out lpUserTime);

       return lpKernelTime + lpUserTime;
   }
+4

DateTime.Now.Ticks?

, , , .

+1

DateTime, TimeSpan. TimeSpan, .

var before = DateTime.Now;
System.Threading.Thread.Sleep(6500);
var after = DateTime.Now;

var timeTaken = after - before;
var secondsTaken = timeTaken.TotalSeconds;
var milisecondsTaken = timeTaken.TotalMiliseconds;

Please note that you must use TotalXXXXto get everything XXXX, otherwise it will be more like what a person wants. In this case timeTaken.Seconds = 5, but timeTaken.TotalSeconds = 65.

+1
source

Here is sample code to use the System.Diagnostics.Stopwatch class:

Stopwatch sw = Stopwatch.StartNew();
// Put the code here that you want to time
sw.Stop();
long elapsedTime = sw.ElapsedMilliseconds;

DateTime.Ticks is only accurate to 15 ms, so it is not suitable for short synchronization algorithms.

0
source

Source: https://habr.com/ru/post/1705338/


All Articles