@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface PerformanceTest { int warmUpIterations() default 10; int measurementIterations() default 10; int fork() default 1; int threads() default 1; } @SupportedAnnotationTypes("com.example.PerformanceTest") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class PerformanceTestProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { if (element.getKind() != ElementKind.METHOD) { continue; } PerformanceTest performanceTest = element.getAnnotation(PerformanceTest.class); generateJmhCode(element, performanceTest); } } return true; } private void generateJmhCode(Element methodElement, PerformanceTest performanceTest) { String methodName = methodElement.getSimpleName().toString(); int warmUpIterations = performanceTest.warmUpIterations(); int measurementIterations = performanceTest.measurementIterations(); int fork = performanceTest.fork(); int threads = performanceTest.threads(); String jmhCode = "import org.openjdk.jmh.*; " + "public class " + methodName + "Benchmark { " + " @Benchmark " + " @Warmup(iterations = " + warmUpIterations + ") " + " @Measurement(iterations = " + measurementIterations + ") " + " @Fork(value = " + fork + ") " + " @Threads(value = " + threads + ") " + " public void benchmark() { " + " " + methodName + "(); " + " } " + " private void " + methodName + "() { " " + " } " + " public static void main(String[] args) throws Exception { " + " org.openjdk.jmh.Main.main(args); " + " } " + "} "; String packageName = ((PackageElement) methodElement.getEnclosingElement()).getQualifiedName().toString(); try { JavaFileObject fileObject = processingEnv.getFiler().createSourceFile(packageName + "." + methodName + "Benchmark", methodElement); Writer writer = fileObject.openWriter(); writer.write(jmhCode); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } com.example.PerformanceTestProcessor


上一篇:
下一篇:
切换中文