Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure time with C# (.Net Core)

Tags:

c#

.net-core

I know this question has been asked more than once, but I'm not sure if the results I'm having are right. The operation seems too fast, so I'd like to double check if that's really it.

I have a routine that splits a string into a List<byte[]>. I wanted to check the time it takes for the operation, so I modified the code to be like the following:

// Deserializes base64 received from POST service
var str = JsonConvert.DeserializeObject<JsonText>(body).text;

Stopwatch stopWatch = Stopwatch.StartNew();

// parseText is a routine that splits str into
// byte[] of maximum size 100 and puts them into
// a List<byte[]> that is then returned 
commands = DummyClass.parseText(str);

stopWatch.Stop();
TimeSpan timespan = stopWatch.Elapsed;

Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));

...

I ran the routine using a 8000 character string and expected a couple miliseconds op time, but surprisingly the whole operation runs to at most 0.8ms which I expected to be a whole lot slower.

Am I reading the measurements wrong? Does 0.8 means 8ms? Did I do something wrong while measuring the time?

Thank you very much!

like image 281
Tutch Avatar asked May 31 '17 11:05

Tutch


People also ask

How do I measure time in C?

To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.

Is there a time function in C?

C library function - time() The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.

What is C clock?

Description. The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.

What is measure in C?

C = coulomb (electric charge) c = speed of light (velocity) cable = cable length (length) cable length = 720 ft (length) cal = calorie (energy)


1 Answers

Instead of

TimeSpan timespan = stopWatch.Elapsed;
Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));

Why not try

Console.WriteLine("Elapsed time {0} ms",stopWatch.ElapsedMilliseconds);

You want milliseconds, you have them in stopwatch class directly - no need to visit string.format and timespan libraries.

like image 145
SlightlyKosumi Avatar answered Oct 06 '22 13:10

SlightlyKosumi