Measure the time caused by a function and not understand why the time difference is negative

I am trying to check how long a function takes to execute in my code:

I have done this:

void foo()
{

int time = System.DateTime.Now.Millisecond;

// code of my function. do this, that, etc.

Console.WriteLine((System.DateTime.Now.Millisecond-time).ToString());

}

What I understand:

-247

I do not understand why the minus ?? & Amp; please tell me how to measure the time spent by the function. & Amp; If pro-filer is an option, then please recommend me some simple options.

Note. Here I showed a console application, but in practice I need for a web application in ASP.NET, which can also be an n-tier architecture.

thank

+3
source share
5 answers

DateTime.Millisecond /, /.

Stopwatch:

var stopwatch = Stopwatch.StartNew();

// ...

Console.WriteLine(stopwatch.ElapsedMilliseconds);
+22

,

.

  • 2010-01-01 00: 00: 00: 999 → System.DateTime.Now.Millisecond - 999
  • 2010-01-01 00: 00: 01: 000 → System.DateTime.Now.Millisecond is 000

000 - 999 = -999; !

DateTime.Now . , , , System.Diagnostics.Stopwatch: -

void Foo()
{
  Stopwatch myStopWatch = StopWatch.StartNew()

  // Your code goes here;

  Console.WriteLine(myStopWatch.ElapsedMilliseconds);
}

" " .

+2

DateTime.Millisecond .
, 1000.
, , 0.

Stopwatch.

+1

Millisecond , 0 999.

As others have said, you can use the StopWatch class , or you can call DateTime.Subtract () to get a TimeSpan instance , then use the TotalMilliseconds property of that instance to get the total number of milliseconds elapsed between your two times:

public void Foo()
{
    DateTime then = DateTime.Now;
    // ...
    Console.WriteLine(DateTime.Now.Subtract(then).TotalMilliseconds);
}
+1
source

You can use Stopwatch .

0
source

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


All Articles