用于性能跟踪的Java自定义注释

用于性能跟踪的Java自定义注释,java,performance,annotations,Java,Performance,Annotations,我想衡量我的项目中各种功能的性能。这将在多个线程上运行,所以现在我有类似的东西 long start = System.currentTimeMillis(); first(); StatsTracker.putTime("first", System.currentTimeMillis() - start); ... start = System.currentTimeMillis(); second(); StatsTracker.putTime("second", System.curre

我想衡量我的项目中各种功能的性能。这将在多个线程上运行,所以现在我有类似的东西

long start = System.currentTimeMillis();
first();
StatsTracker.putTime("first", System.currentTimeMillis() - start);
...
start = System.currentTimeMillis();
second();
StatsTracker.putTime("second", System.currentTimeMillis() - start);
@StartTime("first")
first();
@EndTime("first")
...
@StartTime("second")
second();
@EndTime("second")
其中StatsTracker是一个静态类,它只跟踪性能图

我刚开始编写自定义注释,我在网上看到的一些教程让我有点困惑。我最终想要的是这样的东西

long start = System.currentTimeMillis();
first();
StatsTracker.putTime("first", System.currentTimeMillis() - start);
...
start = System.currentTimeMillis();
second();
StatsTracker.putTime("second", System.currentTimeMillis() - start);
@StartTime("first")
first();
@EndTime("first")
...
@StartTime("second")
second();
@EndTime("second")
然后对于开始/结束时间注释,我希望这两个注释记录当前系统时间,然后将该运行时间放入映射(记录平均性能)

编辑:在定义函数之前,有这样的内容可能更自然:

@TrackTime("first")
public void first() { ... }

感谢您的帮助。谢谢

注释只是元数据。他们什么也不做

框架可以使用反射来获取方法和类的注释。这意味着,要做您想做的事情,您需要使用AOP来查找方法上的注释并测量它们所花费的时间

这样的框架是存在的(比如Jamon与springbean的组合)。但是,自己编写一个应用程序比现在要花更多的时间,并且可能会迫使您更改应用程序的架构,以便使用某种形式的依赖注入。或者,您必须使用AspectJ插入字节码


所以我的建议是:不要改变任何东西,或者使用依赖注入框架并使用现有产品(例如jamon),或者编写自定义AOP拦截器来测量组件方法所花费的时间。

啊,好吧,我没有意识到这一点。我将Java注释与Python装饰器相关联,并希望它们能做类似的事情:\感谢您的建议!首先,第一个示例不仅更简单,而且更快,因为许多支持注释的AOP框架都有开销。顺便说一句,我会使用System.nanoTime()并预热代码,即分别测量前10000个调用。