/// <summary> /// Attempts to ping a given ip on a given port. /// <para>returns GameNetworkUtilities.INVALID_SERVER incase of failure.</para> /// </summary> /// <param name="ip">IP to ping.</param> /// <param name="port">the ip's open port to ping.</param> /// <returns>ServerStats of the server or GameNetworkUtilities.INVALID_SERVER incase of failure.</returns> public static ServerStats pingIP(string ip, int port) { ServerStats serverStats = INVALID_SERVER; using (Ping ping = new Ping()) { PingReply pingReply = ping.Send(ip, PING_TIMEOUT); if (pingReply != null && pingReply.Status == IPStatus.Success) { try { using (var client = new TcpClient()) { IAsyncResult asyncResult = client.BeginConnect(ip, port, null, null); if (asyncResult.AsyncWaitHandle.WaitOne(PORT_CHECK_TIMEOUT)) { using (StreamWriter streamWriter = new StreamWriter(client.GetStream())) using (StreamReader streamReader = new StreamReader(client.GetStream())) { streamWriter.WriteLine("PING"); streamWriter.Flush(); string[] serverReply = streamReader.ReadLine().Split(game.GameNetworkManager.NETWORK_MSG_SEPARATOR); client.EndConnect(asyncResult); serverStats = new ServerStats(ip, pingReply.RoundtripTime, serverReply[0], serverReply[1]); } } } } catch (SocketException) { } } } return(serverStats); }
public ServerStats GetServerStats(Models.Server server) { var serverStats = new ServerStats(); var statistics = server.Statistics; serverStats.TotalMatchesPlayed = statistics.TotalMatchesPlayed; var mostPopularDay = DateServerStats.GetMostPopularDayForServer(server); if (mostPopularDay != null) { serverStats.MaximumMatchesPerDay = mostPopularDay.MatchesPlayed; } var totalDays = TimeHelper.GetUtcNumberOfDaysBetween(statistics.FirstMatchTimestamp, Matches.GetLastMatchTimestampAmongAllServers()); serverStats.AverageMatchesPerDay = (double)serverStats.TotalMatchesPlayed / totalDays; serverStats.MaximumPopulation = statistics.MaximumPopulation; serverStats.AveragePopulation = (double)statistics.SumOfPopulations / serverStats.TotalMatchesPlayed; serverStats.Top5GameModes = ServerGameModeStats.FindTopGameModesForServer(server, ServerStats.TopGameModesCount) .Select(gm => gm.GameMode.Name) .ToArray(); serverStats.Top5Maps = ServerMapStats.FindTopMapsForServer(server, ServerStats.TopMapsCount) .Select(map => map.Map.Name) .ToArray(); return(serverStats); }
static Dictionary <IPEndPoint, List <int> > Slabs() { ServerStats stats = client.Stats("items"); Type t = stats.GetType(); FieldInfo field_Results = t.GetField("results", BindingFlags.Instance | BindingFlags.NonPublic); Dictionary <IPEndPoint, Dictionary <string, string> > results = field_Results.GetValue(stats) as Dictionary <IPEndPoint, Dictionary <string, string> >; Dictionary <IPEndPoint, Dictionary <string, string> > .Enumerator re = results.GetEnumerator(); Dictionary <IPEndPoint, List <int> > servers = new Dictionary <IPEndPoint, List <int> >(); while (re.MoveNext()) { List <int> members = new List <int>(); re.Current.Value.Keys.ToList().ForEach(key => { Match match = Regex.Match(key, @"items:(?<slab>\d+):number"); int slab = 0; if (match.Success == true && int.TryParse(match.Groups["slab"].Value, out slab)) { members.Add(slab); } }); servers.Add(re.Current.Key, members); } return(servers); }
private void SetServerStats(IGrouping <string, KeyValuePair <string, string> > serverstats) { if (serverstats != null) { var serverstatsdict = serverstats.ToDictionary(x => x.Key, x => x.Value); ServerStatistics = new ServerStats { RedisVersion = serverstatsdict["redis_version"], GitSHA1 = serverstatsdict["redis_git_sha1"], GitDirty = serverstatsdict["redis_git_dirty"], BuildId = serverstatsdict["redis_build_id"], Mode = serverstatsdict["redis_mode"], ArchBits = serverstatsdict["arch_bits"], ConfigFile = serverstatsdict["config_file"], GCCVersion = serverstatsdict.ContainsKey("gcc_version") ? serverstatsdict["gcc_version"] : string.Empty, HZ = serverstatsdict["hz"], LRUClock = serverstatsdict["lru_clock"], MultiplexingApi = serverstatsdict["multiplexing_api"], OS = serverstatsdict["os"], ProcessId = serverstatsdict["process_id"], RunId = serverstatsdict["run_id"], TCPPort = serverstatsdict["tcp_port"], UptimeInDays = serverstatsdict["uptime_in_days"], UptimeInSeconds = serverstatsdict["uptime_in_seconds"] }; } }
private async Task FetchServerStats(ServiceDbContext context, Server server) { var stats = new ServerStats { Server = server, TrackedAt = DateTime.Now }; var infoUrl = new Url(server.GameEndpoint).AppendPathSegment("GetServerInformation"); try { var serverInformation = JsonConvert.DeserializeObject <ServerInformation>( await infoUrl.WithHeader("User-Agent", "SBRW-ServerMonitor") .WithHeader("Accept", "application/json").GetStringAsync()); stats.Status = ServerStatus.Online; stats.PlayersOnline = serverInformation.NumOnline; stats.PlayersRegistered = serverInformation.NumRegistered; } catch (Exception e) { stats.Status = ServerStatus.Offline; _logger.LogError(e, "Failed to fetch stats for {Name} @ {Endpoint}", server.Name, infoUrl); } context.Add(stats); }
public DateTime LoadCSV(string file) { mStats.Clear(); bool skip = true; foreach (var line in File.ReadAllLines(file)) { if (skip) { skip = false; string[] split = line.Split(','); mSessionID = UUID.Parse(split[split.Length - 1]); continue; } ServerStats s = new ServerStats(line, mConfig); mStats.Add(s); } string[] splitFilename = Path.GetFileNameWithoutExtension(file).Split(new char[] { '-' }, 2); mConfig.RunInfo = splitFilename[0]; DateTime ret = DateTime.ParseExact(splitFilename[1], mConfig.TimestampFormat, new DateTimeFormatInfo()); Logger.Info("Loaded pre recorded statistics from: " + file + "."); return(ret); }
public ServerStats GetData() { LNSServer _server = server_1; lock (_server.thelock) { ServerStats o = new ServerStats(); foreach (var game in _server.games) { GameStats gameStats = new GameStats(); gameStats.gameid = game.Key; gameStats.totalRooms = game.Value.rooms.Count; foreach (var room in game.Value.rooms) { gameStats.totalClients += room.Value.playerCount; } o.games.Add(gameStats); } o.totalGames = _server.games.Count; o.totalClients = _server.clients.Count; return(o); } }
public static string CombineStats(ExperimentalConfig config, ServerStats server, ClientStats client, int count) { DateTime ts = server.TimeStamp; string line = client.TimeStamp.ToString(config.TimestampFormat) + ","; line += (config.Timestamp - ts).TotalMilliseconds + ","; line += count + ","; foreach (var key in config.OutputKeys) { switch (key.ToUpper()) { case "CFPS": line += client.CFPS.Aggregate("", (s, v) => s + v + ",", f => f); break; case "POLYGONS": line += client.Polys.Aggregate("", (s, v) => s + v + ",", f => f); break; case "PING": line += client.Ping.Aggregate("", (s, v) => s + v + ",", f => f); break; case "FT": line += server.FrameTime.ToString() + ","; break; case "SFPS": line += server.SFPS.ToString() + ","; break; } } return(line + "," + ((server.TimeStamp - client.TimeStamp).TotalMilliseconds)); }
public void ServerStats_IsEmpty_ShouldReturnFalse_WhenStatsNotEmpty() { var stats = ServerStats.CreateEmpty(); stats.MaximumPopulation = 1; stats.IsEmpty().Should().BeFalse(); }
public Guid Invoke(IDSFDataObject dataObject, out ErrorResultTO errors) { var result = GlobalConstants.NullDataListID; var time = new Stopwatch(); time.Start(); errors = new ErrorResultTO(); if (dataObject.Environment.HasErrors()) { errors.AddError(dataObject.Environment.FetchErrors()); DispatchDebugErrors(errors, dataObject, StateType.Before); } errors.ClearErrors(); try { errors = TryInvokeService(dataObject, errors); } finally { time.Stop(); ServerStats.IncrementTotalRequests(); ServerStats.IncrementTotalTime(time.ElapsedMilliseconds); DispatchDebugErrors(errors, dataObject, StateType.End); } return(result); }
private static async Task Run(IServiceScope scope) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <ServersStatsBackgroundService> >(); var appDbContext = scope.ServiceProvider.GetRequiredService <AppDbContext>(); var bbbClient = scope.ServiceProvider.GetRequiredService <IBBBClient>(); var servers = await appDbContext.Servers.Include(s => s.Meetings.Where(m => m.Running)).ToListAsync(); logger.LogDebug($"Refreshing stats of {servers.Count} servers."); foreach (var server in servers) { var up = true; var stats = new ServerStats(); try { var response = await bbbClient.GetMeetings(server.Url, server.Secret); SetStats(stats, response); CheckMeetings(server, response); } catch (Exception ex) // Maybe be more specific? { logger.LogError(ex, $"Exception while fetching meetings for '{server.Url}'."); up = false; } stats.Up = up; server.Up = up; server.Load = stats.MeetingsCount * 0.9 + stats.ParticipantCount * 0.1; server.Stats.Add(stats); } await appDbContext.SaveChangesAsync(); }
public static void SaveStats(object state) { try { long ticks = DateTime.Now.Ticks; long time = ticks - m_lastMeasureTick; m_lastMeasureTick = ticks; time /= 10000000L; if (time < 1) { log.Warn("Time has not changed since last call of SaveStats"); time = 1; // prevent division by zero? } long inRate = (Statistics.BytesIn - m_lastBytesIn) / time; long outRate = (Statistics.BytesOut - m_lastBytesOut) / time; m_lastBytesIn = Statistics.BytesIn; m_lastBytesOut = Statistics.BytesOut; int clients = WorldMgr.GetAllPlayingClientsCount(); float cpu = 0; if (m_systemCpuUsedCounter != null) { cpu = m_systemCpuUsedCounter.NextValue(); } if (m_processCpuUsedCounter != null) { cpu = m_processCpuUsedCounter.NextValue(); } long totalmem = GC.GetTotalMemory(false); ServerStats newstat = new ServerStats(); newstat.CPU = cpu; newstat.Clients = clients; newstat.Upload = (int)outRate / 1024; newstat.Download = (int)inRate / 1024; newstat.Memory = totalmem / 1024; GameServer.Database.AddObject(newstat); GameServer.Database.SaveObject(newstat); } catch (Exception e) { log.Error("Updating server stats", e); } finally { lock (typeof(StatSave)) { if (m_timer != null) { m_timer.Change(m_statFrequency, Timeout.Infinite); } } } }
/// <summary> /// 使用配置文件默认配置的情况 /// </summary> private MemcachedService() { memClient = new MemcachedClient(); serverInfo = memClient.Stats(); //服务器节点失效事件 memClient.NodeFailed += memClient_NodeFailed; }
/// <summary> /// 使用自定义节点的情况 /// </summary> /// <param name="sectionName"></param> private MemcachedService(string sectionName) { memClient = new MemcachedClient(sectionName); serverInfo = memClient.Stats(); //服务器节点失效事件,需要一个参数为IMemcachedNode并且无返回值的处理器 memClient.NodeFailed += memClient_NodeFailed; }
public QualifiedService([NotNull] ServiceLocation serviceLocation, ServerStats serverStats) { ServiceLocation = serviceLocation; ServerStats = serverStats; IsHealthy = ServerStats != null; }
public Database(MrPing mrPing, IBotMethods botMethods) { activeChallenges = new List <Challenge>(); stats = new ServerStats(); this.mrPing = mrPing; this.botMethods = botMethods; LoadDatabase(); }
public void MarkServerUnavailable() { if (ServerStats == null) { return; } ServerStats.AddUnavailableCount(); }
private void OnServerStatsChanged(ServerStats stats) { if (InvokeRequired) { Invoke((Action)(() => OnServerStatsChanged(stats))); return; } lblActiveBots.Text = stats.ActiveBotsCount.ToString(); }
public static bool IsEmpty(this ServerStats s) { return(s.TotalMatchesPlayed == 0 && s.MaximumMatchesPerDay == 0 && s.AverageMatchesPerDay == 0 && s.MaximumPopulation == 0 && s.AveragePopulation == 0 && s.Top5GameModes.Equals(Array.Empty <GameMode>()) && s.Top5Maps.Equals(Array.Empty <string>())); }
public SlabStatisticsDto GetMetadata() { SlabStatisticsDto resultMetadata = new SlabStatisticsDto(); IMemcachedClient client = this.GetMemcachedClient(); ServerStats stats = client.Stats(); return(resultMetadata); }
public StatisticsDto GetStatistics() { StatisticsDto resultStats = new StatisticsDto(); IMemcachedClient client = this.GetMemcachedClient(); ServerStats stats = client.Stats(); return(resultStats); }
public override async Task CallService(HttpContext context) { var index = context.Request.Path.Value.LastIndexOf('/'); if (index > 0) { var serviceName = context.Request.Path.Value.Substring(index + 1); List <IService> services; if (_routingData.ServicesWithHealthChecks.TryGetValue(serviceName, out services)) { var response = new ServerStats[services.Count]; for (var i = 0; i < services.Count; i++) { var service = services[i]; var usage = service as IUsageInfo; if (usage == null) { continue; } double averageRequestTime = 0; if (usage.Calls > 0) { averageRequestTime = usage.TotalRequestTime / usage.Calls; } response[i] = new ServerStats { ServiceId = service.ServiceId, NodeId = service.NodeId, Calls = usage.Calls, AverageRequestTime = averageRequestTime }; } await context.Response.WriteJsonAsync(response); context.Response.StatusCode = (int)HttpStatusCode.OK; } else { await context.Response.WriteAsync("Unknown server " + serviceName); context.Response.StatusCode = (int)HttpStatusCode.NotFound; } } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; } }
private void LoadDatabase() { if (File.Exists(Path.Combine(mrPing.BotMethods.GetCommandInstanceDataPath(this, mrPing), "challenges.json"))) { activeChallenges = JsonConvert.DeserializeObject <List <Challenge> >(File.ReadAllText(Path.Combine(mrPing.BotMethods.GetCommandInstanceDataPath(this, mrPing), "challenges.json"))); } if (File.Exists(Path.Combine(mrPing.BotMethods.GetCommandInstanceDataPath(this, mrPing), "stats.json"))) { stats = JsonConvert.DeserializeObject <ServerStats>(File.ReadAllText(Path.Combine(mrPing.BotMethods.GetCommandInstanceDataPath(this, mrPing), "stats.json"))); } }
public override async Task CallService(HttpContext context) { var index = context.Request.Path.Value.LastIndexOf('/'); if (index > 0) { var serviceName = context.Request.Path.Value.Substring(index + 1); var services = _store.GetServiceInstances(serviceName); if (services.Any()) { var response = new ServerStats[services.Count]; for (var i = 0; i < services.Count; i++) { var service = services[i]; var usage = service as IUsageInfo; if (usage == null) { continue; } double averageRequestTime = 0; if (usage.Calls > 0) { averageRequestTime = usage.TotalRequestTime / usage.Calls; } response[i] = new ServerStats { ServiceId = service.ServiceId, NodeId = service.NodeId, Calls = usage.Calls, AverageRequestTime = averageRequestTime, LastRequest = usage.LastRequest, LastRequestTime = usage.LastRequestTime, Summary = service.GetSummary() }; } context.Response.StatusCode = (int)HttpStatusCode.OK; await context.Response.WriteJsonAsync(response); } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; await context.Response.WriteAsync("Unknown server " + serviceName); } } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; } }
void Core_Tick() { mRecording = true; mLastStat = new ServerStats(Sim.Stats, Core.Frames.Count(), mConfig); lock (mStats) { if (!mConfig.OneSecMininum || mLastServerStatSec != mLastStat.TimeStamp.Second) { mStats.Add(mLastStat); mLastServerStatSec = mLastStat.TimeStamp.Second; } } }
internal static ServerData CreateServer( string pipeName = null, CompilerHost compilerHost = null, ConnectionHost connectionHost = null, Action <object, EventArgs> onListening = null) { pipeName = pipeName ?? Guid.NewGuid().ToString(); compilerHost = compilerHost ?? CompilerHost.Create(); connectionHost = connectionHost ?? ConnectionHost.Create(pipeName); var serverStatsSource = new TaskCompletionSource <ServerStats>(); var serverListenSource = new TaskCompletionSource <bool>(); var cts = new CancellationTokenSource(); var mutexName = MutexName.GetServerMutexName(pipeName); var thread = new Thread(_ => { var eventBus = new TestableEventBus(); eventBus.Listening += (sender, e) => { serverListenSource.TrySetResult(true); }; if (onListening != null) { eventBus.Listening += (sender, e) => onListening(sender, e); } try { RunServer( pipeName, connectionHost, compilerHost, cts.Token, eventBus, Timeout.InfiniteTimeSpan); } finally { var serverStats = new ServerStats(connections: eventBus.ConnectionCount, completedConnections: eventBus.CompletedCount); serverStatsSource.SetResult(serverStats); } }); thread.Start(); // The contract of this function is that it will return once the server has started. Spin here until // we can verify the server has started or simply failed to start. while (ServerConnection.WasServerMutexOpen(mutexName) != true && thread.IsAlive) { Thread.Yield(); } return(new ServerData(cts, pipeName, serverStatsSource.Task, serverListenSource.Task)); }
private void CollectBoltData() { ServerStats localStats = new ServerStats(); localStats.Fps = (short)(1.0f / Time.deltaTime); localStats.Timestamp = Time.time; foreach (BoltConnection conn in BoltNetwork.Clients) { ClientStats c = new ClientStats(); c.IpAddress = conn.RemoteEndPoint.Address.ToString(); c.Port = conn.RemoteEndPoint.Port; localStats.Clients.Add(c); } this.stats = localStats; }
private static void AssertCorrectReport(LoadReportingGrpc.LoadReportingGrpcClient client, ServiceLoad actualLoad) { var loadResponse = client.ReportLoad(new LoadReportRequest { ServiceName = ServiceName }); Assert.NotNull(loadResponse.ServerStats); ServerStats serverStats = loadResponse.ServerStats; Assert.AreEqual(actualLoad.ProcessCapacity, serverStats.RequestCapacity); Assert.AreEqual(actualLoad.CurrentProcessCount, serverStats.CurrentRequests); Assert.AreEqual(actualLoad.ServerUtilization, serverStats.ServerUtilization); }
public override Task <LoadReportResponse> ReportLoad(LoadReportRequest request, ServerCallContext context) { var result = new LoadReportResponse(); var serverStats = new ServerStats(); result.ServerStats = serverStats; try { if (!_loadByService.TryGetValue(request.ServiceName, out IServiceLoad currentLoad)) { // Unknown service; return(Task.FromException <LoadReportResponse>( new RpcException(new Status(StatusCode.OutOfRange, $"Service name {request.ServiceName} not found.")))); } if (currentLoad == null) { // Unknown load or unknown service; return(Task.FromException <LoadReportResponse>( new RpcException(new Status(StatusCode.OutOfRange, $"Service {request.ServiceName} has no load.")))); } result.TimestampTicks = currentLoad.ReportStart.Ticks; result.KnownLoadRate = currentLoad.KnownLoadRate; serverStats.RequestCapacity = currentLoad.ProcessCapacity; serverStats.CurrentRequests = currentLoad.CurrentProcessCount; serverStats.ServerUtilization = currentLoad.ServerUtilization; currentLoad.Reset(); } catch (Exception e) { var rpcException = new RpcException( new Status(StatusCode.Internal, e.ToString()), e.Message); return(Task.FromException <LoadReportResponse>(rpcException)); } return(Task.FromResult(result)); }
public ServerStats Stats() { var command = new Command { RequestLine = "stats", ExpectData = line => Regex.IsMatch(line, "^OK \\d+$") }; BeginCommand(command); command.Wait(); try { return(ServerStats.Parse(LoadYaml(command.ResponseData))); } catch (Exception) { throw new BeanstalkdException(BeanstalkdExceptionCode.UnexpectedResponse); } }
private void WindowLoaded1(object sender, RoutedEventArgs e) { var lw = new LoginWindow(); if (lw.ShowDialog() != true) { Environment.Exit(0); } Title = lw.Hostbox.Text; Connection.Callback = message => { if (string.IsNullOrEmpty(message)) { return; } if (SevereRegex.IsMatch(message)) { var d = ErrParser.ParseText("\u001b[31m" + message); Dispatcher.Invoke(() => errorOutput.Document.Blocks.Add(d), DispatcherPriority.Background); Dispatcher.Invoke(() => errorOutput.ScrollToEnd(), DispatcherPriority.Background); } else if (WarningRegex.IsMatch(message)) { var d = ErrParser.ParseText("\u001b[33m" + message); Dispatcher.Invoke(() => errorOutput.Document.Blocks.Add(d), DispatcherPriority.Background); Dispatcher.Invoke(() => errorOutput.ScrollToEnd(), DispatcherPriority.Background); } else if (ChestshopRegex.IsMatch(message)) { var d = ShpParser.ParseText(message); Dispatcher.Invoke(() => chestshopOutput.Document.Blocks.Add(d), DispatcherPriority.Background); Dispatcher.Invoke(() => chestshopOutput.ScrollToEnd(), DispatcherPriority.Background); } else { var d = StdParser.ParseText(message); Dispatcher.Invoke(() => consoleOutput.Document.Blocks.Add(d), DispatcherPriority.Background); Dispatcher.Invoke(() => consoleOutput.ScrollToEnd(), DispatcherPriority.Background); } }; new Thread(() => { Thread.CurrentThread.Name = "ServerStatsThread"; try { serverStats = ServerStats.ParseResponse(new WebClient().DownloadString(Connection.ServerIp)); Dispatcher.Invoke(PopulateServerInfo); } catch (Exception ex) { Debug.WriteLine(ex); } }).Start(); }
private void RefreshServerInfo(object sender, RoutedEventArgs e) { new Thread(async () => { while (await Connection.Write("###pong")) { Thread.Sleep(60000); } }).Start(); new Thread(() => { Thread.CurrentThread.Name = "ServerStatsThread"; try { serverStats = ServerStats.ParseResponse(new WebClient().DownloadString(Connection.ServerIp)); Dispatcher.Invoke(PopulateServerInfo); } catch (Exception ex) { Debug.WriteLine(ex); } }).Start(); }
public void Update(ServerStats serverStats) { DownloadSpeed = serverStats.DownloadSpeed.ToSizeString(serverStats.SpeedUnits); UploadSpeed = serverStats.UploadSpeed.ToSizeString(serverStats.SpeedUnits); DefaultDownloadLocation = serverStats.DefaultDownloadLocation; RemainingSpace = serverStats.SpaceRemaining.ToSizeString(serverStats.SizeUnits); if (!IsLoaded) { IsLoaded = true; _eventAggregator.GetEvent<ServerLoaded>().Publish(true); } }
protected override bool ExecuteAction() { Dictionary<IPEndPoint, Dictionary<string, string>> retval = new Dictionary<IPEndPoint, Dictionary<string, string>>(); foreach (MemcachedNode server in ServerPool.WorkingServers) { using (PooledSocket ps = server.Acquire()) { if (ps == null) continue; ps.SendCommand("stats"); Dictionary<string, string> serverData = new Dictionary<string, string>(StringComparer.Ordinal); while (true) { string line = ps.ReadResponse(); // stat values are terminated by END if (String.Compare(line, "END", StringComparison.Ordinal) == 0) break; // expected response is STAT item_name item_value if (line.Length < 6 || String.Compare(line, 0, "STAT ", 0, 5, StringComparison.Ordinal) != 0) { if (log.IsWarnEnabled) log.Warn("Unknow response: " + line); continue; } // get the key&value string[] parts = line.Remove(0, 5).Split(' '); if (parts.Length != 2) { if (log.IsWarnEnabled) log.Warn("Unknow response: " + line); continue; } // store the stat item serverData[parts[0]] = parts[1]; } retval[server.EndPoint] = serverData; } } results = new ServerStats(retval); return true; }
void Core_Tick() { mRecording = true; mLastStat = new ServerStats(Sim.Stats, Core.Frames.Count(), mConfig); lock (mServerStats) { if (!mConfig.OneSecMininum || mLastServerStatSec != mLastStat.TimeStamp.Second) { mServerStats.Add(mLastStat); mLastServerStatSec = mLastStat.TimeStamp.Second; } } }
public DateTime LoadCSV(string file) { mServerStats.Clear(); bool skip = true; foreach (var line in File.ReadAllLines(file)) { if (skip) { skip = false; string[] split = line.Split(','); mSessionID = UUID.Parse(split[split.Length - 1]); continue; } ServerStats s = new ServerStats(line, mConfig); mServerStats.Add(s); ClientStats c = new ClientStats(line, mConfig); mClientStats.Add(c); } string[] splitFilename = Path.GetFileNameWithoutExtension(file).Split(new char[] { '-' }, 2); mConfig.RunInfo = splitFilename[0]; DateTime ret = DateTime.ParseExact(splitFilename[1], mConfig.TimestampFormat, new DateTimeFormatInfo()); Logger.Info("Loaded pre recorded statistics from: " + file + "."); return ret; }
public static string CombineStats(ExperimentalConfig config, ServerStats server, ClientStats client, int count) { DateTime ts = server.TimeStamp; string line = client.TimeStamp.ToString(config.TimestampFormat) + ","; line += (config.Timestamp - ts).TotalMilliseconds + ","; line += count + ","; foreach (var key in config.OutputKeys) { switch (key.ToUpper()) { case "CFPS": line += client.CFPS.Aggregate("", (s, v) => s + v + ",", f => f); break; case "POLYGONS": line += client.Polys.Aggregate("", (s, v) => s + v + ",", f => f); break; case "PING": line += client.Ping.Aggregate("", (s, v) => s + v + ",", f => f); break; case "FT": line += server.FrameTime.ToString() + ","; break; case "SFPS": line += server.SFPS.ToString() + ","; break; } } return line + "," + ((server.TimeStamp - client.TimeStamp).TotalMilliseconds); }