-2

I have this code:

  var userId = Int32.Parse(User.Identity.GetUserId());
  using (var context = new IdentityContext())
  {
      roleId = context.Database.SqlQuery<int>("SELECT RoleId FROM AspNetUserRoles where UserId = " + userId).FirstOrDefault();
  }

Is there a very quick and simple way I could time how long this takes to execute. Even if the answer is put into a variable after this code block that would be enough as I can debug and see how long it took.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

4 Answers4

3

Use stopwatch :

using System.Diagnostics;

...

Stopwatch stopWatch = new Stopwatch();

stopWatch.Start();

var userId = Int32.Parse(User.Identity.GetUserId());
  using (var context = new IdentityContext())
  {
      roleId = context.Database.SqlQuery<int>("SELECT RoleId FROM AspNetUserRoles where UserId = " + userId).FirstOrDefault();
  }

stopWatch.Stop();

TimeSpan ts = stopWatch.Elapsed;

string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds / 10);
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

u can put this code before the region:

DateTime start = DateTime.Now;

and this code after it:

DateTime end = DateTime.Now;
TimeSpan span = end - start;

and then in debug mode you can see the value of span;

1

Stopwatch is your friend

    // Create new stopwatch
     Stopwatch stopwatch = new Stopwatch();

     // Begin timing
     stopwatch.Start();

     // Do something
     for (int i = 0; i < 1000; i++)
     {
         Thread.Sleep(1);
     }

     // Stop timing
     stopwatch.Stop();
Kypros
  • 2,997
  • 5
  • 21
  • 27
4nis
  • 99
  • 2
1

You have four options, at least.

Small test project I did...

DateTime Checker

DateTime begin = DateTime.UtcNow;
//what you want to control...
DateTime end = DateTime.UtcNow;
Console.WriteLine("DateTime.UtcNow measured time: {0} ms", (end - begin).TotalMilliseconds);

Progress Checker

using System.Diagnostics;

...

TimeSpan begin = Process.GetCurrentProcess().TotalProcessorTime;
//what you want to control...
TimeSpan end = Process.GetCurrentProcess().TotalProcessorTime;
Console.WriteLine("Process.TotalProcessor measured time: {0} ms", (end - begin).TotalMilliseconds);

StopWatch Checker

using System.Diagnostics;

...

Stopwatch watch = new Stopwatch();
watch.Start();
//what you want to control...
watch.Stop();
Console.WriteLine("Stopwatch measured time: {0} ms", watch.ElapsedMilliseconds);

TickCounter Checker

int start = Environment.TickCount;
//what you want to control...
int duration = Environment.TickCount - start;
Console.WriteLine("TickCount measured time: {0} ms", duration);
blfuentes
  • 2,731
  • 5
  • 44
  • 72