代码C:
/*
* Created on 2005-3-21
*/
/**
* @author jtzhu
*/
using System;
internal class NoSuchElementException:System.Exception{};
public class list {
internal class Element
{
internal int datum;
internal Element next;
internal Element(int datum, Element next)
{
this.datum = datum;
this.next = next;
}
}
internal class Iter
{
Element curr;
internal Iter(Element head)
{
this.curr = head;
}
internal bool hasNext()
{
return curr != null;
}
internal int next()
{
if(curr == null)
throw new NoSuchElementException();
int result = curr.datum;
curr = curr.next;
return result;
}
};
Element head;
Element tail;
list()
{
head = tail = null;
}
bool isEmpty()
{
return head == null;
}
void purge()
{
Element curr = head;
Element next;
while(curr!=null)
{
next = curr.next;
curr = next;
}
head = tail = null;
}
void append(int datum)
{
if(head == null)
{
head = tail = new Element(datum,null);
}
else
{
tail.next = new Element(datum, null);
tail = tail.next;
}
}
void extract(int datum)
{
if(isEmpty())
throw new NoSuchElementException();
Element curr = head;
Element pre = null;
while(curr != null && curr.datum != datum)
{
pre = curr;
curr = curr.next;
}
if(curr == null)
throw new NoSuchElementException();
if(curr == head)
{
Element next = head.next;
head = next;
}
else
{
pre.next = curr.next;
}
if(curr == tail)
tail = pre;
}
void assign(list another)
{
if(this == another)
return;
Iter iter = another.iterator();
purge();
while(iter.hasNext())
{
append(iter.next());
}
}
Iter iterator()
{
return new Iter(head);
}
public static void Main() {
list from = new list();
list to = new list();
const int length = 100000;
const int innerLoops = 100;
for(int i=0;i<length;i++)
from.append(i);
DateTime start,end;
double timeuse;
for(int i=0;i<3;i++)
{
Console.Write("loop "+i+":\n");
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.purge();
start = DateTime.Now;
for(int j=0;j<length;j++)
to.append(j);
end = DateTime.Now;
timeuse+= (end-start).TotalMilliseconds;
}
Console.Write("append: "+length/timeuse*innerLoops/1000+"M/s\t");
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.purge();
start = DateTime.Now;
to.assign(from);
end = DateTime.Now;
timeuse+= (end-start).TotalMilliseconds;
}
Console.Write("assign: "+innerLoops/timeuse*1000+"/s\t");
start = DateTime.Now;
for(int j=length/2;j<(length/2+1000);j++)
to.extract(j);
end = DateTime.Now;
timeuse=(end-start).TotalMilliseconds;
Console.Write("extract: "+1000/timeuse+"k/s\t");
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.assign(from);
start = DateTime.Now;
to.purge();
end = DateTime.Now;
timeuse+= (end-start).TotalMilliseconds;
}
Console.Write("purge: "+innerLoops/timeuse*1000+"/s\n");
}
}
}
编译方式:
csc list.cs
本文地址:http://com.8s8s.com/it/it22756.htm