What I would recommend you to do here is to create an instance of Stopwatch
by Stopwatch.StartNew
, execute your method or your code that you want to calculate execution time. Stop the Stopwatch
where you think you method should be done with execution, and then get ElapsedMilliseconds
like I will do in code below:
@{
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
if (i % 100000 == 0)
{
@Html.Raw("<p>" + i.ToString() + "</p> <br />");
}
}
stopwatch.Stop();
@Html.Raw("<p>Elapsed time is: " + stopwatch.ElapsedMilliseconds.ToString() + "</p>");
}
And please, in case you might get an Error while you are trying to execute this code, be sure that you've included System.Diagnostics;
P.S If you don't like stopwatch.ElapsedMilliseconds
you might check also for stopwatch.Elapsed
to display elapsed time..
As I can see after Alexander's comment that you want start time, end time etc, what I suggest you to do here is to create a custom Stopwatch by inheriting System.Diagnostics.Stopwatch
class and extending it with a couple of DateTime properties.
And I will now show you how you might do it:
public class MyCustomStopWatch : Stopwatch
{
public DateTime? StartAt { get; private set; }
public DateTime? EndAt { get; private set; }
public void Reset()
{
StartAt = null;
EndAt = null;
base.Reset();
}
public void Restart()
{
StartAt = DateTime.Now;
EndAt = null;
base.Restart();
}
//This is what is important to you right now, to get data about that when you code started, and when your code finished with executing
public void Start()
{
StartAt = DateTime.Now;
base.Start();
}
public void Stop()
{
EndAt = DateTime.Now;
base.Stop();
}
}
If you are wondering HOW COULD I USE THAT CODE?
DON'T WORRY, HERE IS AN EXAMPLE BASED ON YOUR QUESTION:
@{
MyCustomStopwatch stopwatch = MyCustomStopwatch();
for (int i = 0; i < 1000000; i++)
{
if (i % 100000 == 0)
{
@Html.Raw("<p>" + i.ToString() + "</p> <br />");
}
}
stopwatch.Stop();
@Html.Raw(String.Format("<p>Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2} </p>", stopwatch.ElapsedMilliseconds.ToString(), stopwatch.StartAt.Value.ToString(), stopwatch.EndAt.Value.ToString());
}
Whatever I hope that you catch up the point and I hope that this helped you to solve your problem