.NETFramework:Stopwatch

本文介绍如何利用.NET Framework中的Stopwatch类进行精确的时间测量。Stopwatch类提供了多种方法来启动、停止、重启计时器,以及获取经过的时间。通过示例代码展示了如何开始和结束计时过程并获取耗时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ylbtech-.NETFramework:Stopwatch

 

1.返回顶部
1、
#region 程序集 System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.dll
#endregion

namespace System.Diagnostics
{
    //
    // 摘要:
    //     提供一组方法和属性,可用于准确地测量运行时间。若要浏览此类型的.NET Framework 源代码,请参阅 Reference Source。
    public class Stopwatch
    {
        //
        // 摘要:
        //     获取以每秒刻度数表示的计时器频率。 此字段为只读。
        public static readonly long Frequency;
        //
        // 摘要:
        //     指示计时器是否基于高分辨率性能计数器。 此字段为只读。
        public static readonly bool IsHighResolution;

        //
        // 摘要:
        //     初始化 System.Diagnostics.Stopwatch 类的新实例。
        public Stopwatch();

        //
        // 摘要:
        //     获取一个值,该值表示 System.Diagnostics.Stopwatch 计时器是否正在运行。
        //
        // 返回结果:
        //     如果 System.Diagnostics.Stopwatch 实例当前正在运行,并且正在测量时间间隔花费的时间,则为 true;否则为 false。
        public bool IsRunning { get; }
        //
        // 摘要:
        //     获取当前实例测量得出的总运行时间。
        //
        // 返回结果:
        //     一个只读的 System.TimeSpan,表示当前实例测量得出的总运行时间。
        public TimeSpan Elapsed { get; }
        //
        // 摘要:
        //     获取当前实例测量得出的总运行时间(以毫秒为单位)。
        //
        // 返回结果:
        //     一个只读长整型,表示当前实例测量得出的总毫秒数。
        public long ElapsedMilliseconds { get; }
        //
        // 摘要:
        //     获取当前实例测量得出的总运行时间(用计时器刻度表示)。
        //
        // 返回结果:
        //     一个只读长整型,表示当前实例测量得出的计时器刻度总数。
        public long ElapsedTicks { get; }

        //
        // 摘要:
        //     获取计时器机制中的当前刻度数。
        //
        // 返回结果:
        //     一个长整型,表示基础计时器机制中的刻度计数器值。
        public static long GetTimestamp();
        //
        // 摘要:
        //     初始化新的 System.Diagnostics.Stopwatch 实例,将运行时间属性设置为零,然后开始测量运行时间。
        //
        // 返回结果:
        //     刚刚开始测量运行时间的 System.Diagnostics.Stopwatch。
        public static Stopwatch StartNew();
        //
        // 摘要:
        //     停止时间间隔测量,并将运行时间重置为零。
        public void Reset();
        //
        // 摘要:
        //     停止时间间隔测量,将运行时间重置为零,然后开始测量运行时间。
        public void Restart();
        //
        // 摘要:
        //     开始或继续测量某个时间间隔的运行时间。
        public void Start();
        //
        // 摘要:
        //     停止测量某个时间间隔的运行时间。
        public void Stop();
    }
}
2、
2.返回顶部
1、
#region Stopwatch计时器
        /// <summary>
        /// 计时器开始
        /// </summary>
        /// <returns></returns>
        public static Stopwatch TimerStart()
        {
            Stopwatch watch = new Stopwatch();
            watch.Reset();
            watch.Start();
            return watch;
        }
        /// <summary>
        /// 计时器结束
        /// </summary>
        /// <param name="watch"></param>
        /// <returns></returns>
        public static string TimerEnd(Stopwatch watch)
        {
            watch.Stop();
            double costtime = watch.ElapsedMilliseconds;
            return costtime.ToString();
        }
        #endregion
2、
3.返回顶部
 
4.返回顶部
 
5.返回顶部
 
 
6.返回顶部
 
warn作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载于:https://www.cnblogs.com/storebook/p/9503742.html

PS C:\Users\Administrator> # 加载必要程序集 - 确保使用正确的方法 PS C:\Users\Administrator> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop PS C:\Users\Administrator> PS C:\Users\Administrator> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression >> ) >> >> $resultTemplate = [PSCustomObject]@{ >> StatusCode = 0 >> StatusMessage = "NotExecuted" >> Headers = [ordered]@{} >> Content = $null >> IsSuccess = $false >> Technology = "None" >> ErrorMessage = $null >> ElapsedMs = 0 >> } >> >> $timer = [System.Diagnostics.Stopwatch]::StartNew() >> $result = $resultTemplate.PSObject.Copy() >> $result.Technology = "HttpClient" >> >> $handler = $null >> $client = $null >> $request = $null >> $response = $null >> >> try { >> # 创建 HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> >> # 修复证书验证 - 兼容旧版 .NET >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> } >> >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建 HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> >> # 修复方法创建 - 兼容旧版 .NET >> $httpMethod = [System.Net.Http.HttpMethod]::new($Method) >> if (-not $httpMethod) { >> $httpMethod = New-Object System.Net.Http.HttpMethod($Method) >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage($httpMethod, $Uri) >> >> # 添加默认 User-Agent >> if (-not $Headers.ContainsKey('User-Agent')) { >> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0") >> } >> >> # 添加自定义头 >> foreach ($key in $Headers.Keys) { >> if (-not $request.Headers.TryAddWithoutValidation($key, $Headers[$key])) { >> if (-not $request.Content) { >> $request.Content = New-Object System.Net.Http.StringContent("") >> } >> $request.Content.Headers.TryAddWithoutValidation($key, $Headers[$key]) >> } >> } >> >> # 处理请求体 >> if ($Body -and @('POST','PUT','PATCH') -contains $Method) { >> if ($Body -is [byte[]]) { >> $request.Content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> elseif ($Body -is [hashtable] -or $Body -is [System.Collections.IDictionary]) { >> $jsonBody = $Body | ConvertTo-Json -Depth 5 -Compress >> $request.Content = New-Object System.Net.Http.StringContent( >> $jsonBody, >> [System.Text.Encoding]::UTF8, >> "application/json" >> ) >> } >> elseif ($Body -is [string]) { >> $request.Content = New-Object System.Net.Http.StringContent( >> $Body, >> [System.Text.Encoding]::UTF8 >> ) >> } >> else { >> throw "Unsupported body type: $($Body.GetType().Name)" >> } >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 解析响应 >> $result.StatusCode = [int]$response.StatusCode >> $result.StatusMessage = $response.ReasonPhrase >> $result.IsSuccess = $response.IsSuccessStatusCode >> >> $result.Headers = [ordered]@{} >> foreach ($header in $response.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> foreach ($header in $response.Content.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> $result.Content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> return $result >> } >> catch [System.Threading.Tasks.TaskCanceledException] { >> $result.ErrorMessage = "Request timed out after $Timeout seconds" >> $result.StatusCode = 408 >> $result.StatusMessage = "Timeout" >> return $result >> } >> catch { >> # 提供更详细的错误信息 >> $result.ErrorMessage = $_.Exception.ToString() >> $result.StatusCode = 500 >> $result.StatusMessage = "HttpRequestError" >> return $result >> } >> finally { >> $timer.Stop() >> $result.ElapsedMs = $timer.ElapsedMilliseconds >> >> # 安全清理资源 >> if ($response -is [IDisposable]) { $response.Dispose() } >> if ($request -is [IDisposable]) { $request.Dispose() } >> if ($client -is [IDisposable]) { $client.Dispose() } >> if ($handler -is [IDisposable]) { $handler.Dispose() } >> } >> } >> PS C:\Users\Administrator> # 使用构造函数替代 Parse 方法 PS C:\Users\Administrator> $httpMethod = [System.Net.Http.HttpMethod]::new($Method) 使用“1”个参数调用“.ctor”时发生异常:“值不能为 null 或空。 参数名: method” 所在位置 行:1 字符: 1 + $httpMethod = [System.Net.Http.HttpMethod]::new($Method) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentException PS C:\Users\Administrator> if (-not $httpMethod) { >> $httpMethod = New-Object System.Net.Http.HttpMethod($Method) >> } >> # 检查对象是否实现了 IDisposable 接口 >> if ($response -is [IDisposable]) { $response.Dispose() } >> New-Object : 找不到构造函数。找不到类型 System.Net.Http.HttpMethod 的相应构造函数。 所在位置 行:2 字符: 19 + $httpMethod = New-Object System.Net.Http.HttpMethod($Method) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand PS C:\Users\Administrator> # 直接保存函数代码,避免包含无效字符 PS C:\Users\Administrator> $fixedModuleCode = @' >> <上面修复后的完整函数代码> >> '@ >> PS C:\Users\Administrator> # 创建模块目录 PS C:\Users\Administrator> $moduleDir = "$env:ProgramFiles\WindowsPowerShell\Modules\PSHttpClient" PS C:\Users\Administrator> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 生成并保存模块文件 PS C:\Users\Administrator> $fixedModuleCode = @' >> # 将上面修复后的完整函数代码复制到这里 >> '@ >> PS C:\Users\Administrator> $fixedModuleCode | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force -PassThru ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 1.3 PSHttpClient PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试用例 PS C:\Users\Administrator> $testCases = @( >> @{Url = "https://httpbin.org/get"; Method = "GET"; ExpectedCode = 200} >> @{Url = "https://httpbin.org/post"; Method = "POST"; Body = @{name="Test"}; ExpectedCode = 200} >> @{Url = "https://self-signed.badssl.com/"; Method = "GET"; SkipCertificateCheck = $true; ExpectedCode = 200} >> @{Url = "https://invalid.domain.abc/"; Method = "GET"; ExpectedCode = 0} >> ) >> PS C:\Users\Administrator> # 执行测试 PS C:\Users\Administrator> $results = foreach ($test in $testCases) { >> $params = @{ >> Uri = $test.Url >> Method = $test.Method >> } >> >> if ($test.Body) { $params['Body'] = $test.Body } >> if ($test.SkipCertificateCheck) { $params['SkipCertificateCheck'] = $true } >> >> $result = Invoke-EnhancedCurlRequest @params >> >> [PSCustomObject]@{ >> TestCase = $test.Url >> Method = $test.Method >> Status = if ($result.StatusCode -eq $test.ExpectedCode) { "✅ PASS" } else { "❌ FAIL" } >> StatusCode = $result.StatusCode >> Expected = $test.ExpectedCode >> Success = $result.IsSuccess >> Tech = $result.Technology >> Error = if ($result.ErrorMessage) { $result.ErrorMessage } else { "None" } >> Time = Get-Date -Format "HH:mm:ss" >> } >> } >> PS C:\Users\Administrator> # 显示结果 PS C:\Users\Administrator> $results | Format-Table -AutoSize TestCase Method Status StatusCode Expected Success Tech Error -------- ------ ------ ---------- -------- ------- ---- ----- https://httpbin.org/get GET ✅ PASS 200 200 True HttpClient None https://httpbin.org/post POST ✅ PASS 200 200 True HttpClient None https://self-signed.badssl.com/ GET ❌ FAIL 500 200 False HttpClient System.Management.Automation.Me... https://invalid.domain.abc/ GET ❌ FAIL 500 0 False HttpClient System.Management.Automation.Me... PS C:\Users\Administrator>
最新发布
08-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值