Which code segment should you use?

You use Microsoft .NET Framework 4.0 to develop an application that connects to a local Microsoft SQL Server 2008 database.
The application can access a high-resolution timer. You need to display the elapsed time, in sub-milliseconds (<1 millisecond),
that a database query takes to execute. Which code segment should you use?

You use Microsoft .NET Framework 4.0 to develop an application that connects to a local Microsoft SQL Server 2008 database.
The application can access a high-resolution timer. You need to display the elapsed time, in sub-milliseconds (<1 millisecond),
that a database query takes to execute. Which code segment should you use?

A.
int Start = Environment.TickCount;
command.ExecuteNonQuery();
int Elapsed = (Environment.TickCount) – Start;
Console.WriteLine(“Time Elapsed: {0:N} ms”, Elapsed);

B.
Stopwatch sw = Stopwatch.StartNew();
command.ExecuteNonQuery() ;
sw.Stop() ;
Console.WriteLine(“Time Elapsed: {0:N} ms”, sw.Elapsed.TotalMilliseconds);

C.
DateTime Start = DateTime.UtcNow;
command.ExecuteNonQuery();
TimeSpan Elapsed = DateTime.UtcNow – Start;
Console.WriteLine(“Time Elapsed: {0:N} ms”, Elapsed.Milliseconds);

D.
Stopwatch sw = new Stopwatch();
sw.Start() ;
command.ExecuteNonQuery();
sw.Stop();
Console.WriteLine(“Time Elapsed: {0:N} ms”, sw.Elapsed.Milliseconds);

Explanation:
Stopwatch Class
(http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx)



Leave a Reply 8

Your email address will not be published. Required fields are marked *


j

j

I think the answer is wrong here

j

j

should be B – TotalMilliseconds which also expresses fractional values

SA

SA

I agree with J

qwer

qwer

Agree with j. Milliseconds is Int64 and will not help with sub-milliseconds (<1 millisecond)

Mike

Mike

Except that StopWatch does not have a TotalMilliseconds property. That’s from TimeSpan.

Mike

Mike

… of course Stopwatch.Elapsed is a TimeSpan.

Gaius

Gaius

The answer should definitely be B.

D is wrong not only because it is the wrong data type, but because it only returns the milliseconds *component* of the elapsed time, not the total time in ms. E.g., for a timespan of 00:00:03.0005000, ts.Milliseconds will return 0. For the same timespan, ts.TotalMilliseconds will return 3000.5, which is what the question wants.

John Galt

John Galt

I agree with Gaius, you want TotalMiliseconds, not just Milliseconds part. The correct answer is B.