using System;
using static System.Console;
namespace ArraySegmentSample
{
class Program
{
static void Main()
{
int[] arr_1 = new int[50000000];
int[] arr_2 = new int[50000000];
for(int i=0;i<100000000;i++)
{
if(i%2==0)
{
arr_1[i/2] = i;
}
else
{
arr_2[i / 2] = i;
}
}
var segments = new ArraySegment<int>[2]
{
new ArraySegment<int>(arr_1,0,50000000),
new ArraySegment<int>(arr_2,0,50000000)
};
var sum = SumOfSegments(segments);
WriteLine("the sum is " + sum);
ReadLine();
}
static int SumOfSegments(ArraySegment<int>[] segments)
{
int sum = 0, offset = 0, i;
//计算时间
//int timeStart = DateTime.Now.Millisecond;
DateTime beforDT = System.DateTime.Now;
//WriteLine(beforDT.Millisecond);
//WriteLine($"the statrt time is {timeStart}");
foreach(var segment in segments)
{
///第一种算法
/* for (i=segment.Offset;i<segment.Offset+segment.Count;i++)
{
sum += segment.Array[i];
}
*/
///第二种算法
for(offset=segment.Offset,i=segment.Offset+segment.Count-1;i>=offset;i--)
{
sum += segment.Array[i];
}
}
//int timeEnd = DateTime.Now.Millisecond;
DateTime afterDT = System.DateTime.Now;
//WriteLine(afterDT.Millisecond);
TimeSpan ts = afterDT.Subtract(beforDT);
// WriteLine($"the end is {timeEnd}");
WriteLine($"the consumed time is {ts.TotalMilliseconds}");
return sum;
}
}
}
第一种运行时间:
the consumed time is 708.0181
the sum is 887459712
第二种运行时间
the consumed time is 446.2979
the sum is 887459712
原因在于第一种算法每次在for循环时都需要计算
segment.Offset和 segment.Count;
而第二种在for循环时只需计算一次,所以性能提升了