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

时间:2015-07-09 23:13:25

标签: c# stopwatch

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

然而,这个控制台应用程序需要大约5-10分钟,最后总毫秒是一个非常奇怪的数字,如100或400.而除法总是0.我真的拿了我的手表,应用程序需要5到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

1 个答案:

答案 0 :(得分:4)

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

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

使用TotalMilliseconds

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