Skip to main content
 首页 » 编程设计

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

2024年02月06日13yyy_WW

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

然而,这个控制台应用程序大约需要 5-10 分钟,最后总毫秒数是一个非常奇怪的数字,例如 100 或 400。而且分度始终为 0。我真的拿走了我的 watch ,应用程序需要 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。

附言您也可以使用相同的 stopwatch.ElapsedMilliseconds。