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

这里给出C#的代码:

1.由于C#已经自带Stopwatch类,所以这个就省下了。

 

2.首先是WorkClass测试类实现

 

//filename:WorkClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csharp_performance_test { 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 ulong fib(ulong n) { if (n < 2) return (1); else return (fib(n - 2) + fib(n - 1)); } public double FibTest() { return (double)fib(30); } } }  

 

3.然后是AutoTestClass类实现

//filename:AutoTestClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Reflection; namespace csharp_performance_test { class AutoTestClass { public void AutoTest(string mname) { const int test_count = 10; double test_time = 0.0, ret = 0.0; int run_count = 0; Stopwatch sw = new Stopwatch(); WorkClass wc = new WorkClass(); Type mytype = typeof(WorkClass); MethodInfo myminfo = mytype.GetMethod(mname); for (run_count = 0; run_count < test_count; run_count++) { ret = 0.0; sw.Reset(); sw.Start(); ret = (double)myminfo.Invoke(wc,null); if (ret > 0) sw.Stop(); else sw.Stop(); test_time += sw.ElapsedMilliseconds; } Console.WriteLine("work cost average time(10)={0} ms", test_time / test_count); } } }  

 

4.最后是主程序

//filename:Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace csharp_performance_test { class Program { static void Main(string[] args) { AutoTestClass atc = new AutoTestClass(); atc.AutoTest("AddTest"); atc.AutoTest("FibTest"); atc.AutoTest("MulTest"); atc.AutoTest("DivTest"); } } } 

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