首页 > 代码库 > C#Stopwatch的使用,性能测试

C#Stopwatch的使用,性能测试

 

一,先开启开始或继续测量某个时间间隔的运行时间,然后停止,最后重置时间,输出.

using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class TestPerformance : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        /*Var 性能测试 */        Stopwatch stw = new Stopwatch();        List<long> intlist = new List<long>();        stw.Start();        for (long i = 0; i < 10000000; i++)        {            var index = i;//使用var转入和转出            intlist.Add(index);        }        stw.Stop();        Label1.Text= stw.Elapsed.Ticks.ToString();         stw.Reset();        /*Int 性能测试 */        List<long> intlist2 = new List<long>();        stw.Start();//开始时间        for (long i = 0; i < 1000000; i++)        {            long index = i;//使用int转入和转出            intlist2.Add(index);        }        stw.Stop();        Label2.Text = stw.Elapsed.Ticks.ToString();        stw.Reset();        /*Object性能测试 */        stw.Start();//开始时间        List<long> intlist3 = new List<long>();        for (long i = 0; i < 1000000; i++)        {            object index = i;//使用object转入和转出            intlist3.Add((long)index);        }        stw.Stop();        Label3.Text = stw.Elapsed.Ticks.ToString();     }}

二,前端显示

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPerformance.aspx.cs" Inherits="TestPerformance" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <form id="form1" runat="server">    <div>        Var:<asp:Label ID="Label1" runat="server" Text="Var"></asp:Label><br/>        Int:<asp:Label ID="Label2" runat="server" Text="Int"></asp:Label><br/>        Object:<asp:Label ID="Label3" runat="server" Text="Object"></asp:Label>    </div>    </form></body></html>

三,显示结果

技术分享

C#Stopwatch的使用,性能测试