protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using var scopedServiceProvider = _scopeFactory.CreateScope(); var start = DateTime.UtcNow; try { using var sw = new SimpleStopwatch(); var middleware = scopedServiceProvider.ServiceProvider.GetService <IMiddleware>(); await middleware.Process(); _logger.LogInformation($"[ CSharpWars Script Processor - PROCESSING {sw.ElapsedMilliseconds}ms! ]"); } catch (Exception ex) { _logger.LogError($"[ CSharpWars Script Processor - EXCEPTION - '{ex.Message}'! ]"); } var timeTaken = DateTime.UtcNow - start; var delay = (int)(timeTaken.TotalMilliseconds < DELAY_MS ? DELAY_MS - timeTaken.TotalMilliseconds : 0); await Task.Delay(delay, stoppingToken); } }
static void Main(string[] args) { Task.Run(async() => { Processor p = new Processor(); while (true) { var start = DateTime.UtcNow; try { using (var sw = new SimpleStopwatch()) { await p.GoPrivate(); Console.WriteLine($"[ BR2017 - {sw.ElapsedMilliseconds}ms! ]"); } } catch (Exception ex) { Console.WriteLine($"[ BR2017 - EXCEPTION - '{ex.Message}'! ]"); } var timeTaken = DateTime.UtcNow - start; var delay = (Int32)(timeTaken.TotalMilliseconds < DELAY_MS ? DELAY_MS - timeTaken.TotalMilliseconds : 0); await Task.Delay(delay); } }).Wait(); }
public async Task SimpleStopwatch_Should_Start_On_Construction() { // Arrange var simpleStopwatch = new SimpleStopwatch(); // Act await Task.Delay(1100); // Assert simpleStopwatch.ElapsedMilliseconds.Should().BeGreaterThan(1000); }
public async Task SimpleStopwatch_Should_Stop_On_Dispose() { // Arrange var simpleStopwatch = new SimpleStopwatch(); // Act simpleStopwatch.Dispose(); await Task.Delay(1100); // Assert simpleStopwatch.ElapsedMilliseconds.Should().BeLessThan(1000); }
public async Task <List <BotStatisticDto> > GetBotStatistics(String teamName, String teamPassword, String arenaName) { using (var sw = new SimpleStopwatch()) { var botStatistics = new List <BotStatisticDto>(); var team = await _dbContext.Teams.SingleOrDefaultAsync(x => x.Name.ToUpper() == teamName.ToUpper()); if (team == null || !Crypt.EnhancedVerify(teamPassword, team.Password)) { return(null); } var arena = await _dbContext.Arenas.SingleOrDefaultAsync(x => x.Name.ToUpper() == arenaName.ToUpper()); if (arena == null) { return(null); } var bots = await _dbContext.Bots.Where(x => x.Deployments.Any(d => d.ArenaId == arena.Id)).ToListAsync(); bots.ForEach(bot => { var botStatistic = _botMapper.Map(bot); botStatistic.PhysicalHealth = new HealthDto { Maximum = bot.MaximumPhysicalHealth, Current = bot.CurrentPhysicalHealth, Drain = bot.PhysicalHealthDrain }; botStatistic.Stamina = new HealthDto { Maximum = bot.MaximumStamina, Current = bot.CurrentStamina, Drain = bot.StaminaDrain }; botStatistic.Location = new PositionDto { X = bot.LocationX, Y = bot.LocationY, }; botStatistic.BotId = bot.Id; botStatistic.BotName = bot.Name; botStatistic.ArenaId = arena.Id; botStatistic.ArenaName = arena.Name; botStatistic.TotalPhysicalDamageDone = bot.PhysicalDamageDone; botStatistic.TotalNumberOfKills = bot.Kills; botStatistic.BotLife = DateTime.UtcNow - bot.TimeOfBirth; botStatistics.Add(botStatistic); }); Debug.WriteLine($"GetBotStatistics - {sw.ElapsedMilliseconds}ms"); return(botStatistics); } }
private async Task <IResult> Try(Func <Task <IResult> > action) { try { using var stopwatch = new SimpleStopwatch(); var result = await action(); _logger.LogTrace($"REQUEST: {stopwatch.ElapsedMilliseconds}ms"); return(result); } catch (LogicException ex) { return(Results.BadRequest(ex.Message)); } }
public async Task <List <TeamStatisticDto> > GetTeamStatistics(String teamName, String teamPassword) { using (var sw = new SimpleStopwatch()) { var teamStatistics = new List <TeamStatisticDto>(); var team = await _dbContext.Teams.SingleOrDefaultAsync(x => x.Name.ToUpper() == teamName.ToUpper()); if (team == null || !Crypt.EnhancedVerify(teamPassword, team.Password)) { return(null); } var arenas = await _dbContext.Arenas.Where(x => x.Active && (!x.Private || x.Name.ToUpper() == teamName.ToUpper())).ToListAsync(); var arenaIds = arenas.Select(x => x.Id); var bots = await _dbContext.Bots.Where(x => x.Deployments.Any(d => arenaIds.Contains(d.ArenaId))) .Include(x => x.Deployments).ToListAsync(); arenas.ForEach(arena => { var bots4Arena = bots.Where(x => x.Deployments.Any(d => d.TeamId == team.Id)).ToList(); var teamStatistic = _teamMapper.Map(team); teamStatistic.ArenaId = arena.Id; teamStatistic.ArenaName = arena.Name; teamStatistic.TeamId = team.Id; teamStatistic.TeamName = team.Name; teamStatistic.NumberOfDeployments = arena.Deployments.Count(x => x.Team.Id == team.Id); teamStatistic.NumberOfLiveBots = bots4Arena.Count(x => x.CurrentPhysicalHealth > 0); teamStatistic.NumberOfDeadBots = bots4Arena.Count(x => x.CurrentPhysicalHealth == 0); var averageBotLife = bots.Where(x => x.TimeOfDeath.HasValue) .Select(x => (x.TimeOfDeath.Value - x.TimeOfBirth).TotalMilliseconds) .AverageOrDefault(Double.MaxValue); teamStatistic.AverageBotLife = averageBotLife == Double.MaxValue ? TimeSpan.MaxValue : TimeSpan.FromMilliseconds(averageBotLife); teamStatistic.TotalNumberOfKills = bots4Arena.Select(x => x.Kills).Sum(); teamStatistic.TotalNumberOfDeaths = bots4Arena.Count(x => x.CurrentPhysicalHealth == 0); teamStatistic.TotalPhysicalDamageDone = bots4Arena.Select(x => x.PhysicalDamageDone).Sum(); teamStatistic.TotalStaminaConsumed = bots4Arena.Select(x => x.MaximumStamina - x.CurrentStamina).Sum(); teamStatistics.Add(teamStatistic); }); Debug.WriteLine($"GetTeamStatistics - {sw.ElapsedMilliseconds}ms"); return(teamStatistics); } }
static async Task MainAsync() { var serviceCollection = new ServiceCollection(); serviceCollection.ConfigurationHelper(c => { c.ConnectionString = GetEnvironmentVariable("CONNECTION_STRING"); c.ArenaSize = ToInt32(GetEnvironmentVariable("ARENA_SIZE")); }); serviceCollection.ConfigureScriptProcessor(); var serviceProvider = serviceCollection.BuildServiceProvider(); while (true) { using (var scopedServiceProvider = serviceProvider.CreateScope()) { var start = DateTime.UtcNow; try { using (var sw = new SimpleStopwatch()) { var middleware = scopedServiceProvider.ServiceProvider.GetService <IMiddleware>(); await middleware.Process(); WriteLine($"[ CSharpWars Script Processor - PROCESSING {sw.ElapsedMilliseconds}ms! ]"); } } catch (Exception ex) { WriteLine($"[ CSharpWars Script Processor - EXCEPTION - '{ex.Message}'! ]"); } var timeTaken = DateTime.UtcNow - start; var delay = (Int32)(timeTaken.TotalMilliseconds < DELAY_MS ? DELAY_MS - timeTaken.TotalMilliseconds : 0); await Task.Delay(delay); } } }
public async Task Process() { using (var stopwatch = new SimpleStopwatch()) { var arena = await _arenaLogic.GetArena(); var elapsedArena = stopwatch.ElapsedMilliseconds; var bots = await _botLogic.GetAllLiveBots(); var elapsedBots = stopwatch.ElapsedMilliseconds - elapsedArena; var context = ProcessingContext.Build(arena, bots); await _preprocessor.Go(context); var elapsedPreprocessing = stopwatch.ElapsedMilliseconds - elapsedBots - elapsedArena; await _processor.Go(context); var elapsedProcessing = stopwatch.ElapsedMilliseconds - elapsedPreprocessing - elapsedBots - elapsedArena; await _postprocessor.Go(context); var elapsedPostprocessing = stopwatch.ElapsedMilliseconds - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; await _botLogic.UpdateBots(context.Bots); var elapsedUpdateBots = stopwatch.ElapsedMilliseconds - elapsedPostprocessing - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; //await _messageLogic.CreateMessages(context.Messages); var elapsedCreateMessages = stopwatch.ElapsedMilliseconds - elapsedUpdateBots - elapsedPostprocessing - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; Console.WriteLine( $"{elapsedArena}ms, {elapsedBots}ms, {elapsedPreprocessing}ms, {elapsedProcessing}ms, {elapsedPostprocessing}ms, {elapsedUpdateBots}ms, {elapsedCreateMessages}ms"); } }
public async Task Process() { using var stopwatch = new SimpleStopwatch(); var arena = await _arenaLogic.GetArena(); var elapsedArena = stopwatch.ElapsedMilliseconds; var bots = await _botLogic.GetAllLiveBots(); var elapsedBots = stopwatch.ElapsedMilliseconds - elapsedArena; var context = ProcessingContext.Build(arena, bots); await _preprocessor.Go(context); var elapsedPreprocessing = stopwatch.ElapsedMilliseconds - elapsedBots - elapsedArena; await _processor.Go(context); var elapsedProcessing = stopwatch.ElapsedMilliseconds - elapsedPreprocessing - elapsedBots - elapsedArena; await _postprocessor.Go(context); var elapsedPostprocessing = stopwatch.ElapsedMilliseconds - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; await _botLogic.UpdateBots(context.Bots); var elapsedUpdateBots = stopwatch.ElapsedMilliseconds - elapsedPostprocessing - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; //await _messageLogic.CreateMessages(context.Messages); var elapsedCreateMessages = stopwatch.ElapsedMilliseconds - elapsedUpdateBots - elapsedPostprocessing - elapsedProcessing - elapsedPreprocessing - elapsedBots - elapsedArena; _logger.LogInformation("{elapsedArena}ms, {elapsedBots}ms, {elapsedPreprocessing}ms, {elapsedProcessing}ms, {elapsedPostprocessing}ms, {elapsedUpdateBots}ms, {elapsedCreateMessages}ms", elapsedArena, elapsedBots, elapsedPreprocessing, elapsedProcessing, elapsedPostprocessing, elapsedUpdateBots, elapsedCreateMessages); }
public async Task <ScriptValidationResponse> Validate(ScriptValidationRequest request) { var scriptValidation = new ScriptValidationResponse(); var botScript = await PrepareScript(request.Script); ImmutableArray <Diagnostic> diagnostics; using (var sw = new SimpleStopwatch()) { diagnostics = botScript.Compile(); scriptValidation.CompilationTimeInMilliseconds = sw.ElapsedMilliseconds; } if (!diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error)) { var task = Task.Run(() => { var arena = new ArenaDto { Width = 10, Height = 10 }; var bot = new BotDto { Id = Guid.NewGuid(), Name = "Bot", MaximumHealth = 100, CurrentHealth = 100, MaximumStamina = 100, CurrentStamina = 100, X = 1, Y = 1, Orientation = PossibleOrientations.South, Memory = new Dictionary <string, string>().Serialize() }; var friendBot = new BotDto { Id = Guid.NewGuid(), Name = "Friend", MaximumHealth = 100, CurrentHealth = 100, MaximumStamina = 100, CurrentStamina = 100, X = 1, Y = 3, Orientation = PossibleOrientations.North }; var enemyBot = new BotDto { Id = Guid.NewGuid(), Name = "Enemy", MaximumHealth = 100, CurrentHealth = 100, MaximumStamina = 100, CurrentStamina = 100, X = 1, Y = 5, Orientation = PossibleOrientations.North }; var botProperties = BotProperties.Build(bot, arena, new[] { bot, friendBot, enemyBot }.ToList()); var scriptGlobals = ScriptGlobals.Build(botProperties); using (var sw = new SimpleStopwatch()) { try { botScript.RunAsync(scriptGlobals).Wait(); } catch (Exception ex) { scriptValidation.ValidationMessages.Add(new ScriptValidationMessage { Message = "Runtime error: " + ex.Message }); } scriptValidation.RunTimeInMilliseconds = sw.ElapsedMilliseconds; } }); if (!task.Wait(TimeSpan.FromSeconds(2))) { scriptValidation.ValidationMessages.Add(new ScriptValidationMessage { Message = "Your script did not finish in a timely fashion!" }); scriptValidation.RunTimeInMilliseconds = long.MaxValue; } } foreach (var diagnostic in diagnostics) { if (diagnostic.Severity == DiagnosticSeverity.Error) { scriptValidation.ValidationMessages.Add(new ScriptValidationMessage { Message = diagnostic.GetMessage(), LocationStart = diagnostic.Location.SourceSpan.Start, LocationEnd = diagnostic.Location.SourceSpan.End }); } } return(scriptValidation); }
public static async Task <ScriptValidationDto> ValidateScript(String script) { var scriptValidation = new ScriptValidationDto { Script = script, Messages = new List <ScriptValidationMessageDto>() }; if (script.Contains("CSharpCompilation")) { scriptValidation.Messages.Add(new ScriptValidationMessageDto { Message = "Script blocked!" }); return(scriptValidation); } var botScript = await PrepareScript(script); ImmutableArray <Diagnostic> diagnostics; using (var sw = new SimpleStopwatch()) { diagnostics = botScript.Compile(); scriptValidation.CompilationTimeInMilliseconds = sw.ElapsedMilliseconds; } if (!diagnostics.Any()) { var task = Task.Run(() => { var arena = new Arena { Width = 10, Height = 10, Name = "Arena" }; var team = new Team { Name = "MyTeam", Password = "******" }; var enemyTeam = new Team { Name = "EnemyTeam", Password = "******" }; var bot = new Bot { Id = Guid.NewGuid(), Name = "Bot", MaximumPhysicalHealth = 100, CurrentPhysicalHealth = 100, MaximumStamina = 100, CurrentStamina = 100, LocationX = 1, LocationY = 1, Orientation = Orientation.South }; var friendBot = new Bot { Id = Guid.NewGuid(), Name = "Friend", MaximumPhysicalHealth = 100, CurrentPhysicalHealth = 100, MaximumStamina = 100, CurrentStamina = 100, LocationX = 1, LocationY = 3, Orientation = Orientation.North }; var enemyBot = new Bot { Id = Guid.NewGuid(), Name = "Enemy", MaximumPhysicalHealth = 100, CurrentPhysicalHealth = 100, MaximumStamina = 100, CurrentStamina = 100, LocationX = 1, LocationY = 5, Orientation = Orientation.North }; var deployment = new Deployment { Arena = arena, Bot = bot, Team = team }; var deploymentFriend = new Deployment { Arena = arena, Bot = friendBot, Team = team }; var deploymentEnemy = new Deployment { Arena = arena, Bot = enemyBot, Team = enemyTeam }; team.Deployments = new List <Deployment> { deployment, deploymentFriend, deploymentEnemy }; bot.Deployments = new List <Deployment> { deployment }; friendBot.Deployments = new List <Deployment> { deploymentFriend }; enemyBot.Deployments = new List <Deployment> { deploymentEnemy }; var coreGlobals = new ScriptGlobals(arena, bot, new[] { bot, friendBot, enemyBot }.ToList()); using (var sw = new SimpleStopwatch()) { try { botScript.RunAsync(coreGlobals).Wait(); } catch (Exception ex) { scriptValidation.Messages.Add(new ScriptValidationMessageDto { Message = "Runtime error: " + ex.Message }); } scriptValidation.RunTimeInMilliseconds = sw.ElapsedMilliseconds; } }); if (!task.Wait(TimeSpan.FromSeconds(1))) { scriptValidation.Messages.Add(new ScriptValidationMessageDto { Message = "Your script did not finish in a timely fashion!" }); scriptValidation.RunTimeInMilliseconds = Int64.MaxValue; } } foreach (var d in diagnostics) { if (d.Severity == DiagnosticSeverity.Error) { scriptValidation.Messages.Add(new ScriptValidationMessageDto { Message = d.GetMessage(), LocationStart = d.Location.SourceSpan.Start, LocationEnd = d.Location.SourceSpan.End }); } } return(scriptValidation); }