时间建设性和破坏性逆转

时间:2013-04-11 04:29:12

标签: c# benchmarking reversing

我有一个家庭作业,我必须建设性地和破坏性地反转数组列表并为列表的不同长度计时。我的Arraylist每次运行都会更新,但它似乎没有在这些方法中注册,因为我没有得到我的时间值,似乎无法找到我的错误。

到目前为止我的代码如下。

public ArrayList ConstructiveReverseDeveloped()
    {            
        ArrayList Temp = new ArrayList();
        for (int i = Developed.Count - 1; i >= 0; i--)
        {
            Apps cur = (Apps)Developed[i];
            Temp.Add(cur);
        }
        return Temp;
    }
    public void TimingConstructive()
    {
        DateTime startTime;
        TimeSpan endTime;
        startTime = DateTime.Now;
        ConstructiveReverseDeveloped();
        endTime = DateTime.Now.Subtract(startTime);
        Console.WriteLine("---------------------------------------------------------");
        Console.WriteLine("Time taken for Constructive Reverse of Developed : {0}", endTime);
    }

public void DestructiveReverseDeveloped()
    {
        //ArrayList x = cloneDeveloped();
        for (int i = Developed.Count - 1; i >= 0; i--)
        {
            Apps cur = (Apps)Developed[i];
            Developed.RemoveAt(i);
            Developed.Add(cur);
        }
    }
    public void TimingDestructive()
    {
        DateTime startTime;
        TimeSpan endTime;
        startTime = DateTime.Now;
        DestructiveReverseDeveloped();
        endTime = DateTime.Now.Subtract(startTime);
        Console.WriteLine("Time taken for Destructive Reverse of Developed : {0}",endTime.ToString());
        Console.WriteLine("---------------------------------------------------------");
    }

你们能指出我正确的方向,为什么我没有获得计时值?我不想要确切的答案,而只是帮助理解。

由于

2 个答案:

答案 0 :(得分:1)

您不希望DateTime.Substract中的DateTime。只需获取TimeSpan(DateTime.Now-startTime)并打印即可。你可能想要打印Total Miliseconds,因为这种操作非常快

答案 1 :(得分:1)

你宁愿拥有一个计时器课程。您的计时方法没有考虑垃圾收集和终结器方法。

这是一个例子

class Timer
{
    private DateTime startingTime;
    // stores starting time of code being tested
    private TimeSpan duration;
    // stores duration of code being tested
    public void startTime()
    {
        GC.Collect();   // force garbage collection
        GC.WaitForPendingFinalizers();
        /* wait until all heap contents finalizer methods have completed for removal of contents to be permanent */
        startingTime = DateTime.Now;
        // get current date/time
    }
    public void stopTime()
    {
        // .Subtract: TimeSpan subtraction
        duration = DateTime.Now.Subtract(startingTime);
    }

    public TimeSpan result()
    {
        return duration;
    }


}

您的代码将类似于

public void TimingDestructive()
{
    Timer Time = new Timer();
    Time.startTime();
    DestructiveReverseDeveloped();
    Time.stopTime();
    Console.WriteLine("Time taken for Destructive Reverse of Developed : {0}ms",Time.result().TotalMilliseconds);
    Console.WriteLine("---------------------------------------------------------");

在执行逆转方法之前,你不应该克隆你的列表吗?如果您计划克隆它们,请在启动计时器和反转方法之前克隆它们。