如何获取一个方法执行的时间? 不知道 .net 中有没有这样的类可以实现?
还有,想用这个时间来做进度条,不知道怎么把它们连起来,可不可以?

解决方案 »

  1.   

            [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
            static extern bool QueryPerformanceCounter(ref long count);        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
            static extern bool QueryPerformanceFrequency(ref long count);        long count = 0;
            long count1 = 0;
            long freq = 0;
            double result = 0;
            
            
            
                QueryPerformanceFrequency(ref freq);
                QueryPerformanceCounter(ref count);
                
                
                执行方法地方
                
                QueryPerformanceCounter(ref count1);
                count = count1 - count;
                result = (double)(count) / (double)freq;
      

  2.   

    var bt = new System.Diagnostics.Stopwatch();
    bt.Start();
    //执行你的方法
    bt.Stop();
    Console.WriteLine(bt.ElapsedMilliseconds);
    定义:
    public class Stopwatch
    {
        private long elapsed;
        public static readonly long Frequency;
        public static readonly bool IsHighResolution;    public static long GetTimestamp();
        public void Reset();
        public void Start();
        public static Stopwatch StartNew();
        public void Stop();    public TimeSpan Elapsed { get; }
        public long ElapsedMilliseconds { get; }
        public long ElapsedTicks { get; }
        public bool IsRunning { get; }
    }
      

  3.   

    连词去DateTime.Now然后相减,这个方法用来统计方法执行时间误差巨大。
      

  4.   

     Stopwatch stw = new Stopwatch();
                    stw.Start();
    你的方法
    stw.Stop();stw.ElapsedMilliseconds就该方法之行的时间