C# codeusing System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
compare();
}
private static void compare()
{
Console.WriteLine("*****比較if-else與三目運算符的效率*****");
for (int j = 1; j < 20; j++)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("這是第" + j + "次測試。");
Console.ForegroundColor = ConsoleColor.White;
Stopwatch time1 = new Stopwatch();
time1.Start();
for (int i = 0; i < 100000000; i++)
{
int temp = 0;
if (temp == 1)
temp = 1;
else
temp = 0;
}
time1.Stop();
TimeSpan t1 = time1.Elapsed;
Console.WriteLine("if-else執行時間是:"+t1.ToString());
time1.Reset();
Stopwatch time2 = new Stopwatch();
time2.Start();
for (int i = 0; i < 100000000; i++)
{
int temp = 0;
temp = temp == 0 ? 1 : 0;
}
time2.Stop();
TimeSpan t2 = time2.Elapsed;
Console.WriteLine("三目運算符執行時間是:" + t2.ToString());
time2.Reset();
string conclusion = (t1 < t2) ? "if-else效率高" : "三目元算符效率高";
float f1 = t1.Ticks;
float f2 = t2.Ticks;
float efficiency = (f1 < f2) ? f2 / f1 : f1 / f2;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("結論是:" + conclusion + ",效率比是:" + efficiency.ToString());
}
Console.WriteLine("*****按下回車鍵關閉窗口*****");
Console.ReadLine();
}
}
}