1

我有一个家庭作业,我必须建设性地和破坏性地反转一个数组列表,并为不同长度的列表计时。我的 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("---------------------------------------------------------");
    }

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

谢谢

4

2 回答 2

1

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

于 2013-04-11T04:37:04.747 回答
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("---------------------------------------------------------");

你不应该在执行你的反转方法之前克隆你的列表吗?如果您确实打算克隆它们,请在开始计时器和反转方法之前克隆它们。

于 2013-04-12T14:18:27.770 回答