CanonSharp/CanonSharp.Benchmark/Benchmarks/GrammarParserBenchmark.cs
jackfiled 89ce313b77 feat: CanonSharp Benchmark. (#4)
Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/4
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
2024-08-19 14:37:34 +08:00

74 lines
2.0 KiB
C#

using BenchmarkDotNet.Attributes;
using CanonSharp.Benchmark.Canon.Core;
using CanonSharp.Benchmark.Canon.Core.Abstractions;
using CanonSharp.Benchmark.Canon.Core.GrammarParser;
using CanonSharp.Benchmark.Canon.Core.LexicalParser;
using CanonSharp.Benchmark.Canon.Core.SyntaxNodes;
using CanonSharp.Pascal.Parser;
using CanonSharp.Pascal.Scanner;
namespace CanonSharp.Benchmark.Benchmarks;
public class GrammarParserBenchmark
{
private readonly List<string> _inputFiles = [];
// CanonSharp
private readonly LexicalScanner _scanner = new();
private readonly GrammarParser _parser = new();
// Canon
private readonly IGrammarParser _grammarParser = GeneratedGrammarParser.Instance;
public GrammarParserBenchmark()
{
_inputFiles.AddRange(ReadOpenSet());
}
[Benchmark]
[ArgumentsSource(nameof(InputFiles))]
public Pascal.SyntaxTree.Program CanonSharpParse(int index)
{
IEnumerable<LexicalToken> tokens = _scanner.Tokenize(new StringReadState(_inputFiles[index]));
return _parser.Parse(tokens);
}
[Benchmark]
[ArgumentsSource(nameof(InputFiles))]
public ProgramStruct CanonParse(int index)
{
Lexer lexer = new();
IEnumerable<SemanticToken> tokens = lexer.Tokenize(new StringSourceReader(_inputFiles[index]));
return _grammarParser.Analyse(tokens);
}
public IEnumerable<object> InputFiles()
{
for (int i = 0; i < _inputFiles.Count; i++)
{
yield return i;
}
}
private static List<string> ReadOpenSet()
{
DirectoryInfo baseDirectory = new("/home/ricardo/Documents/Code/CSharp/CanonSharp/OpenSet");
if (!baseDirectory.Exists)
{
throw new InvalidOperationException("Can't find 'OpenSet' directory.");
}
List<string> result = [];
foreach (FileInfo file in baseDirectory.EnumerateFiles())
{
using StreamReader reader = file.OpenText();
result.Add(reader.ReadToEnd());
}
return result;
}
}