using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace PerformanceTest
{
class Program
{
static List<long> ResponseTimeList = new List<long>();
public static string ReqURL = "";
public static int ReqTotalNumer = 0;
public static int ReqConcurrentNumer = 0;
public static object ob1 = new object();
static void Main(string[] args)
{
Console.WriteLine("************开始测试Web性能************");
Console.WriteLine();
Console.WriteLine("请输入请求URL:");
ReqURL = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("请输入并发用户数(数字):");
string strReqConcurrentNumer = Console.ReadLine();
int.TryParse(strReqConcurrentNumer, out ReqConcurrentNumer);
Console.WriteLine();
Console.WriteLine("请输入请求总次数(数字):");
string strReqTotalNumer = Console.ReadLine();
int.TryParse(strReqTotalNumer, out ReqTotalNumer);
Console.WriteLine();
PerformanceMethond();
Console.WriteLine("************测试中*********************");
Console.WriteLine();
Thread.Sleep(5000);
Console.WriteLine("响应时间总条数:" + ResponseTimeList.Count);
ResponseTimeList.Sort((x, y) => x.CompareTo(y));
#region 平均响应时间
long AverageTime = 0;
long TotalTime = 0;
foreach (long item in ResponseTimeList)
{
TotalTime += item;
}
AverageTime = TotalTime / ReqTotalNumer;
Console.WriteLine("平均响应时间:" + AverageTime + "ms");
#endregion
#region 95%响应时间
long Per95Time = 0;
int Min95 = (Int32)Math.Floor((double)ReqTotalNumer * 0.95);
int Max95 = (Int32)Math.Ceiling((double)ReqTotalNumer * 0.96);
long TotalTime95 = 0;
int Count95 = 0;
for (int i = Min95; i < Max95; i++)
{
TotalTime95 += ResponseTimeList[i];
Count95++;
}
Per95Time =(long)(TotalTime95 / Count95);
Console.WriteLine("95%响应时间:" + Per95Time + "ms");
#endregion
Console.ReadKey();
}
public static void PerformanceMethond()
{
List<string> ConcurrentList = new List<string>();
for (int i = 0; i < ReqConcurrentNumer; i++)
{
ConcurrentList.Add("Request" + i);
}
Parallel.ForEach<String>(ConcurrentList, (item) =>
{
RequestMethodAsync(ReqURL);
});
}
public static void RequestMethodAsync(string URL)
{
int PerNumber = ReqTotalNumer / ReqConcurrentNumer;
for (int i = 0; i < PerNumber; i++)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
HttpClient client = new HttpClient();
client.GetStringAsync(URL);
stopwatch.Stop();
lock (ob1)
{
ResponseTimeList.Add(stopwatch.ElapsedMilliseconds);
}
}
}
}
}
评论