为计时方法调用编写Java批注 [英] Writing a java annotation for timing method call

查看:76
本文介绍了为计时方法调用编写Java批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个对方法调用进行计时的Java注释.像这样的东西:

I want to write a java annotation which times the method call. something like this:

@TimeIt
public int someMethod() { ... }

并且在调用此方法时,它应该在控制台上输出此方法花费了多长时间

and when this method is invoked, it should output on console how long this method took

我知道如何在python中执行此操作,这是我想要执行的操作:

I know how to do it in python, this is what I want it to do:

from time import time, sleep

def time_it(func):
    def wrapper(*args, **kwargs):
        start = time()
        func(*args, **kwargs)
        stop = time()
        print "The function", func.__name__, " took %.3f" % (stop - start)
    wrapper.__name__ = func.__name__
    return wrapper

@time_it
def print_something(*args, **kwargs):
    print "before sleeping"
    print args, kwargs
    sleep(3) # wait 3 seconds
    print "after sleeping"

print_something(1, 2, 3, a="what is this?")

所以我的问题是? 在哪里可以找到一些文档来编写类似的内容,我尝试

So my questions are? Where do I find some documentation to write something like this, I tried apt documentation, had no luck with it. can someone help with writing something like this?

推荐答案

AFAIK,Tomasz正确地说,这不能使用注释来完成.我认为混淆的原因是Python装饰器和Java注释共享相同的语法,但在提供的行为方面却完全不同!

AFAIK, Tomasz is right in saying that this can't be done using annotations. I think the confusion stems from the fact that Python decorators and Java annotations share the same syntax but are completely different in terms of the behavior they offer!

注释是附加到您的类/方法/字段的元数据. 此博客文章的地址使用AOP的计时方法要点.尽管使用Spring,但基本前提保持不变.如果您最好使用AOP编译器,则翻译代码应该不会太困难. 此处.

Annotations are metadata attached to your class/methods/fields. This blog post addresses the point of timing methods using AOP. Though it uses Spring, the basic premise remains the same. If you are good to go with an AOP compiler, it shouldn't be too difficult to translate the code. Another reference (spring specific) here.

编辑:如果您的目的是在不使用完整的分析器的情况下为应用程序提供总体方法计时,则可以使用

EDIT: If your aim is to have a overall method timing for your application without using full blown profilers, you can use hprof for collecting total execution statistics.

这篇关于为计时方法调用编写Java批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆