如何在C#中多次使用秒表?

如何在C#中多次使用秒表?,c#,optimization,time,C#,Optimization,Time,我有执行不同操作的短代码,我想测量执行每个操作所需的时间。我在这里读到有关秒表课的内容,想优化我的时间测量。 我的函数调用其他5个函数,我希望在不声明以下内容的情况下测量每个函数: stopwatch sw1 = new stopwatch(); stopwatch sw2 = new stopwatch(); etc.. 我的函数如下所示: public bool func() { .... func1() func2() .... .... func5() } 有没有办法使用

我有执行不同操作的短代码,我想测量执行每个操作所需的时间。我在这里读到有关秒表课的内容,想优化我的时间测量。 我的函数调用其他5个函数,我希望在不声明以下内容的情况下测量每个函数:

stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..
我的函数如下所示:

public bool func()
{
 ....
 func1()
 func2()
 ....
 ....
 func5()
}
有没有办法使用一个秒表实例来测量时间

谢谢

是的,试试这个:

    void func1()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        func1();
        sw.Stop();
        Console.Write(sw.Elapsed);

        sw.Restart();
        func2();
        sw.Stop();
        Console.Write(sw.Elapsed);
    }
您需要的是Stopwatch类的Restart函数,如下所示:

public bool func()
{
    var stopwatch = Stopwatch.StartNew();

    func1();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();

    func5();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);
}
var ps = new PolyStopwatch();

ps.Start("Method1");
Method1();
ps.Stop();

// other code...

ps.Start("Method2");
Method2();
ps.Stop();

ps.Print();

使用委托将方法作为参数传递给函数

这里我使用动作委托,因为指定的方法不返回值

如果您的方法具有返回类型或参数,则可以使用函数委托对其进行相应修改

    static void Main(string[] args)
    {
        Console.WriteLine("Method 1 Time Elapsed (ms): {0}", TimeMethod(Method1));
        Console.WriteLine("Method 2 Time Elapsed (ms): {0}", TimeMethod(Method2));
    }

    static long TimeMethod(Action methodToTime)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        methodToTime();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }

    static void Method1()
    {
        for (int i = 0; i < 100000; i++)
        {
            for (int j = 0; j < 1000; j++)
            {
            }
        }
    }

    static void Method2()
    {
        for (int i = 0; i < 5000; i++)
        {
        }
    }
}
static void Main(字符串[]args)
{
WriteLine(“方法1经过的时间(ms):{0}”,TimeMethod(Method1));
WriteLine(“方法2经过的时间(毫秒):{0}”,TimeMethod(方法2));
}
静态长时间方法(Action methodToTime)
{
秒表秒表=新秒表();
秒表。开始();
方法时间();
秒表;
返回秒表。延时百万秒;
}
静态void方法1()
{
对于(int i=0;i<100000;i++)
{
对于(int j=0;j<1000;j++)
{
}
}
}
静态void方法2()
{
对于(int i=0;i<5000;i++)
{
}
}
}
通过使用它,您可以传递任何想要的方法


希望有帮助

您可以使用这个小类:

public class PolyStopwatch
{
    readonly Dictionary<string, long> counters;

    readonly Stopwatch stopwatch;

    string currentLabel;

    public PolyStopwatch()
    {
        stopwatch = new Stopwatch();
        counters = new Dictionary<string, long>();
    }

    public void Start(string label)
    {
        if (currentLabel != null) Stop();

        currentLabel = label;
        if (!counters.ContainsKey(label))
            counters.Add(label, 0);
        stopwatch.Restart();
    }

    public void Stop()
    {
        if (currentLabel == null)
            throw new InvalidOperationException("No counter started");

        stopwatch.Stop();
        counters[currentLabel] += stopwatch.ElapsedMilliseconds;
        currentLabel = null;
    }

    public void Print()
    {
        if (currentLabel != null) Stop();

        long totalTime = counters.Values.Sum();
        foreach (KeyValuePair<string, long> kvp in counters)
            Debug.Print("{0,-40}: {1,8:N0} ms ({2:P})", kvp.Key, kvp.Value, (double) kvp.Value / totalTime);
        Debug.WriteLine(new string('-', 62));
        Debug.Print("{0,-40}: {1,8:N0} ms", "Total time", totalTime);
    }
}
如果调用紧随其后,可以省略Stop()

它在循环中运行良好:

for(int i = 0; i < 10000; i++)
{
    ps.Start("Method1");
    Method1();
    ps.Start("Method2");
    Method2();
}
ps.Print();
for(int i=0;i<10000;i++)
{
ps.Start(“方法1”);
方法1();
ps.Start(“方法2”);
方法2();
}
ps.Print();
我使用:

void MyFunc()
    {
        Watcher watcher = new Watcher();
        //Some call
        HightLoadFunc();
        watcher.Tick("My high load tick 1");

        SecondFunc();
        watcher.Tick("Second tick");

        Debug.WriteLine(watcher.Result());
        //Total: 0.8343141s; My high load tick 1: 0.4168064s; Second tick: 0.0010215s;
    }
阶级

类监视程序
{
日期时间开始;
日期时间结束时间;
列表次数=新列表();
公众观察者()
{
start=DateTime.Now;
添加(新的KeyValuePair(开始,“开始”);
结束时间=开始;
}
公共空勾号(字符串消息)
{
添加(新的KeyValuePair(DateTime.Now,message));
}
公共无效结束()
{
endTime=DateTime.Now;
}
公共字符串结果(bool-useNewLine=false)
{
字符串结果=”;
如果(结束时间==开始)
endTime=DateTime.Now;
var total=(endTime-start).TotalSeconds;
结果=$“总计:{Total}s;”;

如果(times.Count)在这种情况下写入sw.Restart和sw.Start之间有任何区别吗?使用Restart停止当前间隔测量并启动新的间隔测量(MSDN)。Restart将清除经过的时间。
void MyFunc()
    {
        Watcher watcher = new Watcher();
        //Some call
        HightLoadFunc();
        watcher.Tick("My high load tick 1");

        SecondFunc();
        watcher.Tick("Second tick");

        Debug.WriteLine(watcher.Result());
        //Total: 0.8343141s; My high load tick 1: 0.4168064s; Second tick: 0.0010215s;
    }
class Watcher
{
    DateTime start;
    DateTime endTime;

    List<KeyValuePair<DateTime, string>> times = new List<KeyValuePair<DateTime, string>>();

    public Watcher()
    {
        start = DateTime.Now;
        times.Add(new KeyValuePair<DateTime, string>(start, "start"));
        endTime = start;
    }

    public void Tick(string message)
    {
        times.Add(new KeyValuePair<DateTime, string>(DateTime.Now, message));
    }

    public void End()
    {
        endTime = DateTime.Now;
    }

    public string Result(bool useNewLine = false)
    {
        string result = "";
        if (endTime == start)
            endTime = DateTime.Now;

        var total = (endTime - start).TotalSeconds;
        result = $"Total: {total}s;";

        if (times.Count <2)
            return result + " Not another times.";
        else 
            for(int i=1; i<times.Count; i++)
            {
                if (useNewLine) result += Environment.NewLine;
                var time = (times[i].Key - times[i - 1].Key).TotalSeconds;
                var m = times[i];
                result += $" {m.Value}: {time}s;";
            }

        return result;
    }
}