1

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

long start = System.currentTimeMillis();
first();
StatsTracker.putTime("first", System.currentTimeMillis() - start);
...
start = System.currentTimeMillis();
second();
StatsTracker.putTime("second", System.currentTimeMillis() - start);

其中 StatsTracker 是一个静态类,它只是跟踪性能图。

我是编写自定义注释的新手,我在网上看到的一些教程让它有点混乱。我最终想要的是这样的

@StartTime("first")
first();
@EndTime("first")
...
@StartTime("second")
second();
@EndTime("second")

然后对于开始/结束时间注释,我希望这两个注释记录当前系统时间,然后将该运行时间放入地图中(以记录平均性能)。

编辑:在函数定义之前有这样的东西可能更自然:

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

任何帮助表示赞赏。谢谢!

4

1 回答 1

2

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

A framework can get the annotations on methods and classes using reflection to do something with them. This means that, to do what you want to do, you would need to use AOP to find the annotations on the methods and measure the time they spent.

Such frameworks exist (like Jamon combined with Spring beans for example). But writing one yourself will take much more time than doing what you're doing now, and will probably force you to change the way your application is architected in order to use some form of dependency injection. Or you'll have to instrument the byte-code with AspectJ for example.

So my advice would be: don't change anything, or use an dependency injection framework and use an existing product (like jamon for example), or write a custom AOP interceptor to measure the time taken by the methods of the components.

于 2013-04-21T21:09:15.250 回答