這裡給出C#的代碼:
1.由於C#已經內建Stopwatch類,所以這個就省下了。
2.首先是WorkClass測試類別實現
//filename:WorkClass.cs<br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />namespace csharp_performance_test<br />{<br /> class WorkClass<br /> {<br /> public double AddTest()<br /> {<br /> int count = 10000000, i = 0, j = 0, count2 = 10;<br /> double sum = 0.0;<br /> for (i = 0; i < count2; i++)<br /> for (j = 0; j < count; j++)<br /> sum += j;<br /> return sum;<br /> }<br /> public double MulTest()<br /> {<br /> int count = 10000 * 10000, i = 0;<br /> double sum = 0.0;<br /> for (i = 1; i < count; i++) sum *= i;<br /> return sum;<br /> }<br /> public double DivTest()<br /> {<br /> int count = 10000 * 10000, i = 0;<br /> double sum = 0.0;<br /> for (i = 1; i < count; i++) sum /= i;<br /> return sum;<br /> }<br /> private ulong fib(ulong n)<br /> {<br /> if (n < 2)<br /> return (1);<br /> else<br /> return (fib(n - 2) + fib(n - 1));<br /> }<br /> public double FibTest()<br /> {<br /> return (double)fib(30);<br /> }<br /> }<br />}<br />
3.然後是AutoTestClass類實現
//filename:AutoTestClass.cs<br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using System.Diagnostics;<br />using System.Reflection;<br />namespace csharp_performance_test<br />{<br /> class AutoTestClass<br /> {<br /> public void AutoTest(string mname)<br /> {<br /> const int test_count = 10;<br /> double test_time = 0.0, ret = 0.0;<br /> int run_count = 0;<br /> Stopwatch sw = new Stopwatch();<br /> WorkClass wc = new WorkClass();<br /> Type mytype = typeof(WorkClass);<br /> MethodInfo myminfo = mytype.GetMethod(mname);<br /> for (run_count = 0; run_count < test_count; run_count++)<br /> {<br /> ret = 0.0;<br /> sw.Reset();<br /> sw.Start();<br /> ret = (double)myminfo.Invoke(wc,null);<br /> if (ret > 0) sw.Stop();<br /> else sw.Stop();<br /> test_time += sw.ElapsedMilliseconds;<br /> }<br /> Console.WriteLine("work cost average time(10)={0} ms", test_time / test_count);<br /> }<br /> }<br />}<br />
4.最後是主程式
<br />//filename:Program.cs<br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using System.Diagnostics;<br />namespace csharp_performance_test<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> AutoTestClass atc = new AutoTestClass();<br /> atc.AutoTest("AddTest");<br /> atc.AutoTest("FibTest");<br /> atc.AutoTest("MulTest");<br /> atc.AutoTest("DivTest");<br /> }<br /> }<br />}