C#使用Stopwatch实现计时功能

 更新时间:2024年03月26日 14:42:18   作者:追逐时光者  
在 C# 中,Stopwatch 类是用于测量经过的时间的工具类,提供了高精度的计时功能,本文主要介绍了C#如何使用Stopwatch实现计时功能,需要的可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

前言

在 C# 中,Stopwatch 类是用于测量经过的时间的工具类,提供了高精度的计时功能。Stopwatch 类位于 System.Diagnostics 命名空间中。通常情况下,使用 Stopwatch 的流程是创建一个 Stopwatch 对象,然后调用 Start 方法开始计时,执行需要测量时间的代码,最后调用 Stop 方法停止计时,并通过 Elapsed 属性获取经过的时间。

Stopwatch 类中常用的方法包括

Start():开始计时。

Stop():停止计时。

Reset():重置计时器。

Restart():重启计时器。

Elapsed:获取经过的时间(Elapsed 属性返回一个 TimeSpan 对象,表示自 Stopwatch 实例开始计时以来经过的时间。你可以通过访问 Elapsed 属性来获取经过的时间)

ElapsedMilliseconds:回一个 long 值,表示自 Stopwatch 实例开始计时以来经过的毫秒数。

ElapsedTicks:返回一个 long 值,表示自 Stopwatch 实例开始计时以来经过的计时周期数。这个值通常用于更精确的时间测量。

使用示例

using System;
using System.Diagnostics;
 
class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
 
        stopwatch.Start();
 
        // 模拟耗时操作
        for (int i = 0; i < 1000000; i++)
        {
            // do something
        }
 
        stopwatch.Stop();
 
        Console.WriteLine($"经过的时间: {stopwatch.Elapsed}");
    }
}

使用总结

通过使用 Stopwatch 类,开发人员可以更准确地测量代码执行的时间,进行性能分析和优化,从而提升应用程序的性能表现。

知识补充

除了上文的内容,小编还为大家整理一些Stopwatch类的其他应用,希望对大家有所帮助

C# StopWatch 实现程序精准计时

下面的示例演示如何使用Stopwatch类来确定应用程序的执行时间。

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        // 开始
        stopWatch.Start();
		
		// 程序执行
        Thread.Sleep(10000);
        
        // 结束
        stopWatch.Stop();
        
        // 获取作为 TimeSpan 值的经过时间。
        TimeSpan ts = stopWatch.Elapsed;

        // 格式化
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);

	    // 打印时间差
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Stopwatch还可以来计算性能数据,示例代码如下:

using System;
using System.Diagnostics;

namespace StopWatchSample
{
    class OperationsTimer
    {
        public static void Main()
        {
            DisplayTimerProperties();

            Console.WriteLine();
            Console.WriteLine("Press the Enter key to begin:");
            Console.ReadLine();
            Console.WriteLine();

            TimeOperations();
        }

        public static void DisplayTimerProperties()
        {
            // Display the timer frequency and resolution.
            if (Stopwatch.IsHighResolution)
            {
                Console.WriteLine("Operations timed using the system's high-resolution performance counter.");
            }
            else
            {
                Console.WriteLine("Operations timed using the DateTime class.");
            }

            long frequency = Stopwatch.Frequency;
            Console.WriteLine("  Timer frequency in ticks per second = {0}",
                frequency);
            long nanosecPerTick = (1000L*1000L*1000L) / frequency;
            Console.WriteLine("  Timer is accurate within {0} nanoseconds",
                nanosecPerTick);
        }

        private static void TimeOperations()
        {
            long nanosecPerTick = (1000L*1000L*1000L) / Stopwatch.Frequency;
            const long numIterations = 10000;

            // Define the operation title names.
            String [] operationNames = {"Operation: Int32.Parse(\"0\")",
                                           "Operation: Int32.TryParse(\"0\")",
                                           "Operation: Int32.Parse(\"a\")",
                                           "Operation: Int32.TryParse(\"a\")"};

            // Time four different implementations for parsing
            // an integer from a string.

            for (int operation = 0; operation <= 3; operation++)
            {
                // Define variables for operation statistics.
                long numTicks = 0;
                long numRollovers = 0;
                long maxTicks = 0;
                long minTicks = Int64.MaxValue;
                int indexFastest = -1;
                int indexSlowest = -1;
                long milliSec = 0;

                Stopwatch time10kOperations = Stopwatch.StartNew();

                // Run the current operation 10001 times.
                // The first execution time will be tossed
                // out, since it can skew the average time.

                for (int i=0; i<=numIterations; i++)
                {
                    long ticksThisTime = 0;
                    int inputNum;
                    Stopwatch timePerParse;

                    switch (operation)
                    {
                        case 0:
                            // Parse a valid integer using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("0");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.

                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 1:
                            // Parse a valid integer using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("0", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 2:
                            // Parse an invalid value using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("a");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 3:
                            // Parse an invalid value using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("a", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;

                        default:
                            break;
                    }

                    // Skip over the time for the first operation,
                    // just in case it caused a one-time
                    // performance hit.
                    if (i == 0)
                    {
                        time10kOperations.Reset();
                        time10kOperations.Start();
                    }
                    else
                    {

                        // Update operation statistics
                        // for iterations 1-10000.
                        if (maxTicks < ticksThisTime)
                        {
                            indexSlowest = i;
                            maxTicks = ticksThisTime;
                        }
                        if (minTicks > ticksThisTime)
                        {
                            indexFastest = i;
                            minTicks = ticksThisTime;
                        }
                        numTicks += ticksThisTime;
                        if (numTicks < ticksThisTime)
                        {
                            // Keep track of rollovers.
                            numRollovers ++;
                        }
                    }
                }

                // Display the statistics for 10000 iterations.

                time10kOperations.Stop();
                milliSec = time10kOperations.ElapsedMilliseconds;

                Console.WriteLine();
                Console.WriteLine("{0} Summary:", operationNames[operation]);
                Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",
                    indexSlowest, numIterations, maxTicks);
                Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",
                    indexFastest, numIterations, minTicks);
                Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds",
                    numTicks / numIterations,
                    (numTicks * nanosecPerTick) / numIterations );
                Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds",
                    numIterations, milliSec);
            }
        }
     }
}

Stopwatch实现对程序运行的精确计时

demo

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StopWatchDemo
{
    class Program
    {
       
        static void Main(string[] args)
        {
            int i = 6000000,m1= 0,m2=0;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int k = 0; k <= i; k++)
            {
                m1++;
            }
            Console.WriteLine(sw.ElapsedMilliseconds);
            sw.Restart();
            for (int k = 0; k <= i; k+=2) 
            {
                m2++;
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}

到此这篇关于C#使用Stopwatch实现计时功能的文章就介绍到这了,更多相关C# Stopwatch计时内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!

相关文章

  • C#给图片添加水印完整实例

    C#给图片添加水印完整实例

    这篇文章主要介绍了C#给图片添加水印的方法,以完整实例形式分析了C#实现文字及图像水印、缩略图、图片剪切等相关技巧,需要的朋友可以参考下
    2015-12-12
  • C#实现学生管理系统

    C#实现学生管理系统

    这篇文章主要为大家详细介绍了C#实现学生管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • C#实现Excel导入sqlite的方法

    C#实现Excel导入sqlite的方法

    这篇文章主要介绍了C#实现Excel导入sqlite的方法,是C#程序设计中非常重要的一个实用技巧,需要的朋友可以参考下
    2014-09-09
  • 在Winform和WPF中注册全局快捷键实现思路及代码

    在Winform和WPF中注册全局快捷键实现思路及代码

    如果注册快捷键,RegisterHotKey中的fsModifiers参数为0,即None选项,一些安全软件会警报,可能因为这样就可以全局监听键盘而造成安全问题,感兴趣的你可以参考下本文
    2013-02-02
  • C#获取指定文件著作权信息的方法

    C#获取指定文件著作权信息的方法

    这篇文章主要介绍了C#获取指定文件著作权信息的方法,涉及C#中FileVersionInfo类的使用技巧,需要的朋友可以参考下
    2015-04-04
  • 浅谈C#数组(一)

    浅谈C#数组(一)

    本篇文章小编要得大家介绍的是C#数组,数组是一种数据结构,它可以包含同一个类型的多个元素,如果需要使用同一类型的多个对象,可以使用数组和集合,需要的朋友可以参考下面文章的具体内容
    2021-09-09
  • C#操作INI文件的辅助类IniHelper

    C#操作INI文件的辅助类IniHelper

    这篇文章主要为大家详细介绍了C#操作INI文件的辅助类IniHelper,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • C#解决文件被占用资源,无法删除或修改的方法

    C#解决文件被占用资源,无法删除或修改的方法

    这篇文章主要介绍C#解决文件被占用资源,比较实用,需要的朋友可以参考下。
    2016-06-06
  • 使用异步方式调用同步方法(实例详解)

    使用异步方式调用同步方法(实例详解)

    .NET Framework 允许您异步调用任何方法。为此,应定义与您要调用的方法具有相同签名的委托;公共语言运行时会自动使用适当的签名为该委托定义BeginInvoke和EndInvoke方法
    2013-10-10
  • C#在新建线程中使用Timer无效问题及解决

    C#在新建线程中使用Timer无效问题及解决

    这篇文章主要介绍了C#在新建线程中使用Timer无效问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08

最新评论


http://www.vxiaotou.com