如何在.py文件中使用%timeit?

时间:2018-07-21 00:05:36

标签: python python-3.x ipython

#include "SportsCar.h"

SportsCar::SportsCar()
{
    Spoilers = false;
    Stripes = false;
}
void SportsCar::PrintCarDetails()
{
    cout << "You have finished your car! You are " <<                                                                         
ColorTypeToString(Color) << " and have " << numdoors << " doors!" << endl;
        if (Spoilers = true)

{
    cout << "Your sports car has some super sweet spoilers and you look like a total baller" << endl;
}
else if (Spoilers = false)
{
    cout << "Your car doesnt have spoilers so you are boring" << endl;
}
if (Stripes = true)
{
    cout << "Your car has stripes and you will often be confused as a racecar" << endl;
}
else if (Stripes = false)
{
    cout << "You dont have stripes but your driving a sports car who can complain" << endl;
}

        }`

尝试了这个,但它没有给我正确的输出。

sort这是一个.py文件,具有简单的功能,可以对列表进行排序。我已经用秒表给它计时了,它比命令返回的内容还要重要。

感谢您的帮助。

编辑:这是一项家庭作业,我必须在命令行中使用%timeit。

2 个答案:

答案 0 :(得分:1)

在我的IPython控制台(带有Python 3.6.5的IPython 6.4.0,安装在Anaconda 5.2下)中,这有效。

%timeit %run sortThis

请注意以下几点。使用%cd magic命令来确保当前工作目录是保存sortThis脚本的目录。或者,或者在命令中包含脚本的路径。另外,如果脚本可以打印任何内容,则在%timeit显示打印结果之前,您可能会在控制台中获得数百或数千个打印副本。

print('Hello, world!')脚本中只有命令sortThis时,我得到了以下结果:

1.23 ms ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

我很确定脚本的第一次加载会导致Python将编译后的版本保存到.pyc文件中,并且该文件在我的计算机缓存中。因此,规定的时间是多次执行的平均时间,导致时间间隔很小。因此,不要指望%timeit安排脚本的首次执行时间-只是许多连续执行的平均值。

答案 1 :(得分:0)

定义脚本的入口点,此函数将脚本顶层的所有内容移入该函数。如果您的旧脚本是

import someStuff

def doStuff(y):
    return someStuff.stuff(y)

x = 100   
print(doStuff(x))

那么您的新脚本将是

import someStuff

def doStuff(y):
    return someStuff.stuff(y)

def main():
    x = 100   
    print(doStuff(x))

if __name__ == '__main__':  
    main()

if __name__ == '__main__' makes the script still runnable directly

然后只需%timeit yourfile.main()