ASP.NET

ASP.NET c# 페이지 로딩 속도 구하는 코드

100ksoft 2024. 11. 8. 13:03

ASP.NET에서 페이지 로딩속도를 표시하기 위해서 Stopwatch class를 사용하여 구현할 수 있습니다.

페이지에서 Top frame,  Left frame 등 Include 페이지를 사용하였을때는 Page_PreRenderComplete 메소드를 사용하여 로딩 속도를 구하면 됩니다.

아래 내용은 페이지 로딩속도 구하는 샘플 코드 입니다.

using System;
using System.Diagnostics;

namespace Test
{
    public partial class TestWrite : System.Web.UI.Page
    {
        // Stopwatch to measure loading time
        private Stopwatch _pageLoadStopwatch;

        protected void Page_Load(object sender, EventArgs e)
        {
            // Initialize and start the stopwatch when the page starts loading
            _pageLoadStopwatch = new Stopwatch();
            _pageLoadStopwatch.Start();
        }
        
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Stop the stopwatch before the page is rendered
            _pageLoadStopwatch.Stop();

            // Calculate the loading time in milliseconds
            double loadTime = _pageLoadStopwatch.Elapsed.TotalMilliseconds;

            // Display the load time on the page (assuming there's a label control)
            lblLoadTime.Text = $"Page loaded in {loadTime:F2} milliseconds.";
        }        

		// 페이지에 include 페이지가 있을때 모든 페이지가 로딩되고 난 후 시간 계산
        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // Stop the stopwatch just before the page and all controls are rendered
            _pageLoadStopwatch.Stop();

            // Calculate the loading time in milliseconds
            double loadTime = _pageLoadStopwatch.Elapsed.TotalMilliseconds;

            // Output the loading time in the page (assuming there's a label control or output)
            lblLoadTime.Text = $"Page loaded in {loadTime:F2} milliseconds.";
        }
    }
}
<!DOCTYPE html>
<html>
<head runat="server">
    <title>Page Load Time Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <!-- User Controls -->
            <uc:UCTop runat="server" id="ucTop" />
            <uc:UCGboLeft runat="server" id="ucLeft" />

            <!-- Label to display the loading time -->
            <asp:Label ID="lblLoadTime" runat="server" Text="Page loading..."></asp:Label>
        </div>
    </form>
</body>
</html>

 

감사합니다.