110,545
社区成员
发帖
与我相关
我的任务
分享
using 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();
}
}
}
Dim j As Integer
For j = 1 To 20
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine("這是第" + CStr(j) + "次測試。")
Console.ForegroundColor = ConsoleColor.White
Dim time1 As Stopwatch = New Stopwatch
time1.Start()
For i As Integer = 1 To 100000000
Dim temp As Integer = 0
If temp = 0 Then
temp = 1
Else
temp = 0
End If
Next
time1.Stop()
Dim t1 As TimeSpan = time1.Elapsed
Console.WriteLine("if-else執行時間是:" + t1.ToString())
time1.Reset()
Dim time2 As Stopwatch = New Stopwatch
time2.Start()
For i As Integer = 1 To 100000000
Dim temp As Integer = 0
temp = IIf(temp = 0, 1, 0)
Next
time2.Stop()
Dim t2 As TimeSpan = time2.Elapsed
Console.WriteLine("三目運算符執行時間是:" + t2.ToString())
time2.Reset()
Dim conclusion As String = IIf(t1 < t2, "if-else效率高", "三目元算符效率高")
Dim f1 As Single = t1.Ticks
Dim f2 As Single = t2.Ticks
Dim efficiency As Single = IIf(f1 < f2, f2 / f1, f1 / f2)
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine("結論是:" + conclusion + ",效率比是:" + efficiency.ToString())
Next
Console.WriteLine("*****按下回車鍵關閉窗口*****")
Console.ReadLine()