关于C和C++,还有c#,还有java程序的速度问题!(四)

这里给出java测试代码

 

1.Stopwatch类的实现

 

//filename:StopWatch.java package my.test; public class StopWatch { private long startTime = 0; private long stopTime = 0; public void start() { this.startTime = System.currentTimeMillis(); } public void stop() { this.stopTime = System.currentTimeMillis(); } //elaspsed time in milliseconds public long getElapsedTime() { long elapsed; elapsed = (stopTime - startTime); return elapsed; } }  

 

2.测试工作类的实现

 

//filename:WorkClass.java package my.test; public class WorkClass { public double AddTest() { int count=10000000,i=0,j=0,count2=10; double sum=0.0; for(i=0;i<count2;i++) for(j=0;j<count;j++) sum+=j; return sum; } public double MulTest() { int count=10000*10000,i=0; double sum=0.0; for(i=1;i<count;i++)sum*=i; return sum; } public double DivTest() { int count=10000*10000,i=0; double sum=0.0; for(i=1;i<count;i++)sum/=i; return sum; } private long fib(long n) { if (n < 2) return (1); else return (fib(n - 2) + fib(n - 1)); } public double FibTest() { return (double)fib(30); } }  

 

3.自动测试类

//filename:AutoTestClass.java package my.test; import java.lang.reflect.Method; public class AutoTestClass { public void AutoTest(String itemname) { int test_count=10; double test_time=0.0; int run_count=0; Double ret; StopWatch sw=new StopWatch(); WorkClass wc=new WorkClass(); try { Class myclass = Class.forName("my.test.WorkClass"); Method mytest_fun = myclass.getMethod(itemname); for(run_count=0;run_count<test_count;run_count++) { ret=0.0; sw.start(); ret=(Double)mytest_fun.invoke(wc,null); if(ret>0)sw.stop(); else sw.stop(); test_time+=sw.getElapsedTime(); } }catch (Throwable e) { System.err.println(e); } String outstr="work cost average time(10)="+test_time/test_count; System.out.println(outstr); } }  

 

4.最后是主程序类

//filename:MainClass.java package my.test; public class MainClass { /** * @param args */ public static void main(String[] args) { AutoTestClass atc=new AutoTestClass(); atc.AutoTest("AddTest"); atc.AutoTest("FibTest"); atc.AutoTest("MulTest"); atc.AutoTest("DivTest"); } }  

你可能感兴趣的:(java,C++,c,String,C#,Class)