Reputation: 73
Is there a way (a class-made in C #) that would allow me to calculate the time required to execute some lines in my program.
Ex :
try
{
string connectionString = GetConnectionString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
***// start counting:
// time = 0***
using (SqlCommand cmd = new SqlCommand(
“SELECT * FROM Books”, conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(“{0}\t{1}\t{2}”,
reader.GetInt32(0),
reader.GetString(1),
reader.GetInt32(2));
}
***// end counting
// time = 10 sec***
}
}
Upvotes: 3
Views: 5145
Reputation: 269278
One option is to use the built-in Stopwatch
class:
var sw = Stopwatch.StartNew();
// do something
sw.Stop();
Console.WriteLine("Time elapsed: {0} milliseconds", sw.ElapsedMilliseconds);
Upvotes: 12
Reputation: 18474
static TimeSpan Time(Action action) {
var sw = StopWatch.StartNew();
action();
sw.Stop();
return sw.Elapsed
}
Then you can just do
var time=Time(() => { // MyCode here });
Upvotes: 1
Reputation: 44696
See the System.Diagnostics.StopWatch class to do it manually or consider using a profiler.
Upvotes: 2