返回计算时间的最佳方法是什么?

时间:2016-07-03 13:56:08

标签: c#

我正在寻找返回某些方法计算时间的最佳方法?例如,我有一个multiplty方法,并且exxted结果是一个整数值,但是如果我的用户想要同时获得(结果和时间)或仅获得int结果,我该怎么办?我认为这种结构不是最好的方式。

2 个答案:

答案 0 :(得分:3)

您可以使用Stopwatch类和output parameter的组合实现它,如下所示:

public int Multiply(int x, int y, out int elapsedMilliseconds) 
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    int result = x * y;

    stopWatch.Stop();

    elapsedMilliseconds = stopWatch.ElapsedMilliseconds;

    return result;
}

// You can also provide this overload to avoid giving the output parameter
// to receive the elapsed time if it's not required at all:
public int Multiply(int x, int y) 
{
    int elapsedMilliseconds;

    return Multiply(x, y, out elapsedMilliseconds);
}

BTW,我怀疑在这种情况下使用秒表毫无意义。如果你在耗时的任务中使用它可能有意义......

答案 1 :(得分:0)

一些让果汁流动的简单方法。不知道你希望如何使用这些东西。

public class Evaluate
{
    public Stopwatch Timer { get; private set; }

    public Evaluate()
    {
        this.Timer = new Stopwatch();
    }

    public static long Elapsed(Action expression)
    {
        Stopwatch timer = Stopwatch.StartNew();
        expression();
        return timer.ElapsedMilliseconds;
    }

    public static T ElapsedWithReturn<T>(Func<T> expression, ref long elapsed)
    {
        Stopwatch timer = Stopwatch.StartNew();
        T result = expression();
        elapsed = timer.ElapsedMilliseconds;
        return result;
    }

    public T IncrementTimer<T>(Func<T> expression)
    {
        this.Timer.Start();
        T result = expression();
        this.Timer.Stop();
        return result;
    }
}

class Program
{
    public static int Multiply(int x, int y)
    {
        int result = x * y;
        return result;
    }

    static void Main()
    {
        int result;
        long elapsed;

        // evaluate a bunch of code using static evaluate function.
        elapsed = Evaluate.Elapsed(() =>
        {
            result = Multiply(1, 2);
            result = Multiply(2, 3);
            result = Multiply(3, 4);
        });

        // evaluate with specific return value, setting elapsed by reference
        result = Evaluate.ElapsedWithReturn(() => Multiply(1, 2), ref elapsed);

        // evaluate with specific return value, getting elapsed over time from class
        Evaluate evaluate = new Evaluate();
        result = evaluate.IncrementTimer(() => Multiply(1, 2));
        result = evaluate.IncrementTimer(() => Multiply(2, 3));
        elapsed = evaluate.Timer.ElapsedMilliseconds;
    }
}