如何使用秒表测量 while 循环迭代平均值

How to measure a while loop iteration average with Stopwatch

我需要知道将一条消息发送到队列需要多长时间(平均),所以我发送了 1000 条,然后将总数除以 1000 t 得到平均值。

但是这个控制台应用程序大约需要 5-10 分钟,最后总毫秒数是一个非常奇怪的数字,例如 100 或 400。而且分度始终为 0。我真的拿走了我的手表,应用程序花费了5 到 10 分钟

我做错了什么来衡量这个?

static void Main(string[] args)
        {
            string queueConnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            QueueClient queueClientEmpresa = QueueClient.CreateFromConnectionString(queueConnectionString, "CapatechSaasApp");

            try
            {
                Console.WriteLine("Testing sending millions of messages");
                int i = 0;
                // Create new stopwatch
                Stopwatch stopwatch = new Stopwatch();

                // Begin timing
                stopwatch.Start();
                while (i < 1000)
                {
                    Empresa empresa = new Empresa()
                    {
                        Nombre = "Empresa:" + i,
                        NIT = "xx",
                        NombreRepresentanteLegal = "xx",
                        TelefonoRepresentanteLegal = "xx",
                        NombreContacto = "x",
                        TelefonoContacto = "x"
                    };
                    i++;

                    BrokeredMessage message = new BrokeredMessage(JsonConvert.SerializeObject(empresa));
                    message.Properties.Add("Operation", "Add");
                    message.Properties.Add("Tipo", "Empresa");
                    queueClientEmpresa.Send(message);

                    //string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
                    //Console.WriteLine("Press key to continue");
                    //Console.ReadKey();
                    //ReceiveMessagesEmpresa(connectionString);                  
                }
                stopwatch.Stop();
                Console.WriteLine("Time elapsed milliseconds: {0}", stopwatch.Elapsed.Milliseconds.ToString());
                Console.WriteLine("Time elapsed milliseconds/1000: {0}", (stopwatch.Elapsed.Milliseconds/1000).ToString());
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

http://screencast.com/t/fjcFRbf2jM

TimeSpan 有多种属性,而您没有使用正确的属性:-)

MilliSeconds 是整个时间跨度的毫秒部分。
TotalMilliSeconds是整个时间,以毫秒表示。

使用TotalMilliseconds.

P.S。您也可以使用相同的 stopwatch.ElapsedMilliseconds