python - 在 Python 中测量带参数的函数的时间

标签 python performance time arguments timeit

我正在尝试测量 raw_queries(...) 的时间,到目前为止没有成功。我发现我应该使用 timeit 模块。问题是我无法(= 我不知道如何)将参数从环境传递给函数。

重要提示:在调用raw_queries之前,我们必须执行phase2()(环​​境初始化)。

旁注:代码在 Python 3 中。

def raw_queries(queries, nlp):
    """ Submit queries without getting visual response """

    for q in queries:
        nlp.query(q)

def evaluate_queries(queries, nlp):
    """ Measure the time that the queries need to return their results """

    t = Timer("raw_queries(queries, nlp)", "?????")
    print(t.timeit())

def phase2():
    """ Load dictionary to memory and subsequently submit queries """

    # prepare Linguistic Processor to submit it the queries
    all_files = get_files()
    b = LinguisticProcessor(all_files)
    b.loadDictionary()

    # load the queries
    queries_file = 'queries.txt'
    queries = load_queries(queries_file)

if __name__ == '__main__':
    phase2()

感谢您的帮助。

更新:我们可以使用 Timer 的第二个参数调用 phase2()。问题是我们需要来自环境的参数 (queries, nlp)

更新:迄今为止最好的解决方案,在 unutbu 的帮助下(仅更改的部分):

def evaluate_queries():
    """ Measure the time that the queries need to return their results """

    t = Timer("main.raw_queries(queries, nlp)", "import main;\
        (queries,nlp)=main.phase2()")

    sf = 'Execution time: {} ms'
    print(sf.format(t.timeit(number=1000)))


def phase2():
    ...

    return queries, b


def main():
    evaluate_queries()

if __name__ == '__main__':
    main()

最佳答案

首先,永远不要使用时间模块来计时函数。很容易得出错误的结论。参见 timeit versus timing decorator举个例子。

为函数调用计时的最简单方法是使用 IPython 的 %timeit 命令。 在那里,您只需启动一个交互式 IPython session ,调用 phase2(),定义 queries, 然后运行

%timeit raw_queries(queries,nlp)

我知道使用 timeit 的第二种最简单的方法是从命令行调用它:

python -mtimeit -s"import test; queries=test.phase2()" "test.raw_queries(queries)"

(在上面的命令中,我假设脚本名为 test.py)

这里的成语是

python -mtimeit -s"SETUP_COMMANDS" "COMMAND_TO_BE_TIMED"

为了能够将queries 传递给raw_queries 函数调用,您必须定义queries 变量。在您发布的代码中,queries 是在 phase2() 中定义的,但仅限于本地。因此,要将 queries 设置为全局变量,您需要执行类似 phase2 返回 queries 的操作:

def phase2():
    ...
    return queries

如果你不想这样搞乱 phase2,创建一个虚拟函数:

def phase3():
    # Do stuff like phase2() but return queries
    return queries

关于python - 在 Python 中测量带参数的函数的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966750/

相关文章:

python - 使用 numpy 求解整数线性系统

python - python单元测试用例中self.assertRaises未涵盖的异常语句

c++ - 更改 std::bitset 中一系列位值的最有效方法

javascript - 计算两个时间值之间的时间差(以分钟为单位)

c# - 如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format ?

python - 在python中顺序读取巨大的CSV文件

python - 读取文件系统中排序的文件

ios - 用于 C/Objective-C/Swift 的快速、粗略的 atan2() 版本?

c++ - 在 C++ 高效存储上,刷新文件策略

java - java多线程是否可以优化多文件写入