简体   繁体   English

如何在C#中计时执行SQL查询?

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

I'm trying to just find out the execution time of my SQL Server query using c#. 我试图找出使用c#的SQL Server查询的执行时间。 I thought a timer would work; 我以为计时器会工作; however I'm new to c# and have been having trouble figuring it out. 但是我是C#的新手,在弄清楚它时遇到了麻烦。 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. 注意:我将其用于测试目的,而不是用于生产目的,因此实际上只有少数人会看到此信息,但这是必需的。

What are you looking for is StopWatch , this is an example: 您在寻找的是StopWatch ,这是一个示例:

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. 检查此问题以了解为什么不应该使用DateTime。

我猜想您是否可以在SQL执行之前和之后获取服务器时间(DateTime.Now),并找到可以让您花费时间的差异。

I was wanting to accomplish the same thing. 我想完成同样的事情。 I've seen StopWatch() but was never able to get it to work. 我看过StopWatch()但是从没能使它正常工作。 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; 您将需要using System.Diagnostics; statement as well in order to print to the debug window . 语句以便打印到debug window

Note: if you're able to get StopWatch() to work for you, then I would definitely recommend that over this. 注意:如果您能够使StopWatch()为您工作,那么我绝对会建议您这样做。 This was just my solution for my code. 这只是我的代码解决方案。

The SQL Query starts executing at SqlCommand.ExecuteReader() , and it's finished executing after the SqlDataReader.Read() returns false. SQL查询从SqlCommand.ExecuteReader()开始执行,并且在SqlDataReader.Read()返回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. 请注意,如果SQL Server的网络速度较慢或有大量结果,则这将无法准确地衡量等待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();
    }

}
DECLARE @Time1 DATETIME

DECLARE @Time2 DATETIME

SET     @Time1 = GETDATE()

-- Insert query here

SET     @Time2 = GETDATE()

SELECT  DATE DIFF(MILLISECOND,@Time1,@Time2) AS Elapsed_MS

this code allows you to show exact time of execution of a specific code segment in your sql query. 此代码使您可以在sql查询中显示执行特定代码段的确切时间。 Place the code that you would like to get the execution time for in the center of the below script. 将您想要获取执行时间的代码放在以下脚本的中央。 The exact time will be shown in the results. 确切的时间将显示在结果中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM