How do I time the execution of an SQL Query in C#?

时间:2018-09-18 20:20:31

标签: c# sql-server timer execution

I'm trying to just find out the execution time of my SQL Server query using c#. I thought a timer would work; however I'm new to c# and have been having trouble figuring it out. I've searched through several questions on this site, and on other sites trying to find out how to time the execution of my query.

Here is my code:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        Console.WriteLine("Executing query...");
        string customerID = "ID_HERE";
        using (SqlConnection connection = new SqlConnection("CONNECTION_STRING"))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand(
                "SELECT col0, col1, col2, col3, col4, col5, col6, col7, col8, col9 FROM Table_name WHERE col1 LIKE @ID", connection))
            {

                command.Parameters.Add(new SqlParameter("ID", customerID));

                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int col0 = reader.GetInt32(0);
                    int col1 = reader.GetInt32(1);
                    string col2 = reader.GetString(2);
                    string col3 = reader.GetString(3);
                    int col4 = reader.GetInt32(4);
                    int col5 = reader.GetInt32(5);
                    short col6 = reader.GetInt16(6);
                    string col7 = reader.GetString(7);
                    string col8 = reader.GetString(8);
                    int col9 = reader.GetInt32(9);
                    Console.WriteLine("col0 = {0}, col1 = {1}, col2 = {2}, col3 = {3}, col4 = {4}, col5 = {5}, col6 = {6}, col7 = {7}, col8 = {8}, col9 = {9}",
                        col0,
                        col1,
                        col2,
                        col3,
                        col4,
                        col5,
                        col6,
                        col7,
                        col8,
                        col9
                        );
                }
            }
        }
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

I'm not sure how to add a timer to this that only times the execution of the query, or even where to put it. I've tried finding other posts about it but none of the ones I've found are similar to this; I could also just be really bad at my searches. Any kind of help would be appreciated, and if you need any more information let me know. I renamed a few things for security, but this is how the code is otherwise. To note: I'm using this for testing purposes, and not for production, so only a few people will ever actually see this but it's necessary.

5 个答案:

答案 0 :(得分:1)

What are you looking for is StopWatch, this is an example:

var watch = System.Diagnostics.Stopwatch.StartNew();
// Run your query
watch.Stop();
//This is the time it took in miliseconds
var elapsedTime = watch.ElapsedMilliseconds;

Check this question for why you shouldn't use DateTime.

答案 1 :(得分:0)

I guess if you get the server time (DateTime.Now) before and after the SQL execution and find the difference that would give you the time elapsed.

答案 2 :(得分:0)

I was wanting to accomplish the same thing. I've seen StopWatch() but was never able to get it to work. So I just rigged my own:

TimeSpan ts = DateTime.Now.TimeOfDay;
Debug.Print("\n\nProcess Started---- " + processName + " ----  " + ts + "\n\n");
/*
 * code here
 */
TimeSpan fts = DateTime.Now.TimeOfDay;
Debug.Print("\n\nProcess Ended---- " + processName + " ----  " + fts + "\n");
Debug.Print("Time Elapsed----  " + (fts - ts) + " \n\n");

It's probably not the fastest or cleanest. But it tells me what I want to know. You will need the using System.Diagnostics; statement as well in order to print to the debug window.

Note: if you're able to get StopWatch() to work for you, then I would definitely recommend that over this. This was just my solution for my code.

答案 3 :(得分:0)

The SQL Query starts executing at SqlCommand.ExecuteReader(), and it's finished executing after the SqlDataReader.Read() returns false. Note that if the SQL Server is across a slow network or there are a large number of results, this won't accurately measure the time spent waiting on the SQL Server.

So

using System;
using System.Data.SqlClient;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Console.WriteLine("Executing query...");
        string customerID = "ID_HERE";
        using (SqlConnection connection = new SqlConnection("CONNECTION_STRING"))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand(
                "SELECT col0, col1, col2, col3, col4, col5, col6, col7, col8, col9 FROM Table_name WHERE col1 LIKE @ID", connection))
            {

                command.Parameters.Add(new SqlParameter("ID", customerID));
                var sw = new Stopwatch();

                sw.Start();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int col0 = reader.GetInt32(0);
                    int col1 = reader.GetInt32(1);
                    string col2 = reader.GetString(2);
                    string col3 = reader.GetString(3);
                    int col4 = reader.GetInt32(4);
                    int col5 = reader.GetInt32(5);
                    short col6 = reader.GetInt16(6);
                    string col7 = reader.GetString(7);
                    string col8 = reader.GetString(8);
                    int col9 = reader.GetInt32(9);
                    Console.WriteLine("col0 = {0}, col1 = {1}, col2 = {2}, col3 = {3}, col4 = {4}, col5 = {5}, col6 = {6}, col7 = {7}, col8 = {8}, col9 = {9}",
                        col0,
                        col1,
                        col2,
                        col3,
                        col4,
                        col5,
                        col6,
                        col7,
                        col8,
                        col9
                        );
                }
                var elapsed = sw.Elapsed;

                Console.WriteLine($"Query Executed and Results Returned in {elapsed.Seconds}sec");
            }
        }
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

答案 4 :(得分:0)

slope

此代码允许您在sql查询中显示执行特定代码段的确切时间。将您想要获取执行时间的代码放在以下脚本的中央。确切的时间将显示在结果中。