How do I get the time in milliseconds?
I want to calculate the time of a bubble sorting algorithm in C #. But it always gives 0. This is my code.
public void bubbleSort(int[] arr, ref double time)
{
var sp = new Stopwatch();
sp.Start();
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
sp.Stop();
time = sp.Elapsed.Milliseconds*1000;
}
basically the time is always 0. What mistake did I make in this code.
source to share
When you receive Milliseconds
, you only receive a millisecond time component. So 1.0501s will only be displayed as 50ms, not 1050.1ms. Also, since this returns int
, you won't see fractional milliseconds, which might be the case for such a short algorithm.
Instead, use TotalMilliseconds
which will return all time in units of milliseconds, and also reconfigure a double
- which includes fractional parts.
source to share
You need to use the TotalMilliseconds
property
Returns the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
time = sp.Elapsed.TotalMilliseconds * 1000;
source to share