我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。

我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。


当前回答

我在查找两种不同方法的运行时间时遇到的问题,这两种方法用于查找所有<=一个数的素数。当在程序中进行用户输入时。

错误的方法

#Sample input for a number 20 
#Sample output [2, 3, 5, 7, 11, 13, 17, 19]
#Total Running time = 0.634 seconds

import time

start_time = time.time()

#Method 1 to find all the prime numbers <= a Number

# Function to check whether a number is prime or not.
def prime_no(num):
if num<2:
    return False
else:
    for i in range(2, num//2+1):
        if num % i == 0:
            return False
    return True

#To print all the values <= n
def Prime_under_num(n):
    a = [2]
    if n <2:
        print("None")
    elif n==2:
        print(2)
    else:
"Neglecting all even numbers as even numbers won't be prime in order to reduce the time complexity."
        for i in range(3, n+1, 2):   
            if prime_no(i):
                a.append(i)
        print(a)


"When Method 1 is only used outputs of running time for different inputs"
#Total Running time = 2.73761 seconds #n = 100
#Total Running time = 3.14781 seconds #n = 1000
#Total Running time = 8.69278 seconds #n = 10000
#Total Running time = 18.73701 seconds #n = 100000

#Method 2 to find all the prime numbers <= a Number

def Prime_under_num(n):
    a = [2]
    if n <2:
        print("None")
    elif n==2:
        print(2)
    else:
        for i in range(3, n+1, 2):   
            if n%i ==0:
                pass
            else:
                a.append(i)
        print(a)

"When Method 2 is only used outputs of running time for different inputs"
# Total Running time = 2.75935 seconds #n = 100
# Total Running time = 2.86332 seconds #n = 1000
# Total Running time = 4.59884 seconds #n = 10000
# Total Running time = 8.55057 seconds #n = 100000

if __name__ == "__main__" :
    n = int(input())
    Prime_under_num(n)
    print("Total Running time = {:.5f} seconds".format(time.time() - start_time))

上述所有情况下获得的不同运行时间都是错误的。对于我们正在接受输入的问题,我们必须在接受输入后才开始计时。这里,用户键入输入所花费的时间也与运行时间一起计算。

正确的方法

我们必须从开头删除start_time=time.time()并将其添加到主块中。

if __name__ == "__main__" :
    n = int(input())
    start_time = time.time()
    Prime_under_num(n)
    print("Total Running time = {:.3f} seconds".format(time.time() - start_time))

因此,两种方法单独使用时的输出如下:-

# Method 1

# Total Running time = 0.00159 seconds #n = 100
# Total Running time = 0.00506 seconds #n = 1000
# Total Running time = 0.22987 seconds #n = 10000
# Total Running time = 18.55819 seconds #n = 100000

# Method 2

# Total Running time = 0.00011 seconds #n = 100
# Total Running time = 0.00118 seconds #n = 1000
# Total Running time = 0.00302 seconds #n = 10000
# Total Running time = 0.01450 seconds #n = 100000

现在我们可以看到,与错误方法相比,总运行时间有显著差异。即使方法2在两种方法中的性能优于方法1,但第一种方法(错误方法)是错误的。

其他回答

首先,以管理员身份打开命令提示符(CMD)并在那里键入,安装人性化的软件包-pip安装人性化

代码:

from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))

输出:

我使用了一个非常简单的函数来计时代码执行的一部分:

import time
def timing():
    start_time = time.time()
    return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))

要使用它,只需在代码之前调用它来度量以检索函数计时,然后在代码之后调用带有注释的函数。时间将显示在评论前面。例如:

t = timing()
train = pd.read_csv('train.csv',
                        dtype={
                            'id': str,
                            'vendor_id': str,
                            'pickup_datetime': str,
                            'dropoff_datetime': str,
                            'passenger_count': int,
                            'pickup_longitude': np.float64,
                            'pickup_latitude': np.float64,
                            'dropoff_longitude': np.float64,
                            'dropoff_latitude': np.float64,
                            'store_and_fwd_flag': str,
                            'trip_duration': int,
                        },
                        parse_dates = ['pickup_datetime', 'dropoff_datetime'],
                   )
t("Loaded {} rows data from 'train'".format(len(train)))

然后输出将如下所示:

[9.35s] Loaded 1458644 rows data from 'train'

我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。

$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"

它运行一次your_module.main()函数,并使用time.time()函数作为计时器打印经过的时间。

要在Python中模拟/usr/bin/time,请参阅带有/usr/bin/time:如何捕获计时信息但忽略所有其他输出?的Python子进程?。

要测量每个函数的CPU时间(例如,不要包括time.sleep()期间的时间),可以使用profile模块(Python 2上的cProfile):

$ python3 -mprofile your_module.py

如果您想使用与配置文件模块相同的计时器,可以将-p传递给上面的timeit命令。

请参见如何评测Python脚本?

我也喜欢Paul McGuire的回答,并提出了一个更符合我需求的上下文管理器表单。

import datetime as dt
import timeit

class TimingManager(object):
    """Context Manager used with the statement 'with' to time some execution.

    Example:

    with TimingManager() as t:
       # Code to time
    """

    clock = timeit.default_timer

    def __enter__(self):
        """
        """
        self.start = self.clock()
        self.log('\n=> Start Timing: {}')

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        """
        self.endlog()

        return False

    def log(self, s, elapsed=None):
        """Log current time and elapsed time if present.
        :param s: Text to display, use '{}' to format the text with
            the current time.
        :param elapsed: Elapsed time to display. Dafault: None, no display.
        """
        print s.format(self._secondsToStr(self.clock()))

        if(elapsed is not None):
            print 'Elapsed time: {}\n'.format(elapsed)

    def endlog(self):
        """Log time for the end of execution with elapsed time.
        """
        self.log('=> End Timing: {}', self.now())

    def now(self):
        """Return current elapsed time as hh:mm:ss string.
        :return: String.
        """
        return str(dt.timedelta(seconds = self.clock() - self.start))

    def _secondsToStr(self, sec):
        """Convert timestamp to h:mm:ss string.
        :param sec: Timestamp.
        """
        return str(dt.datetime.fromtimestamp(sec))

我在查找两种不同方法的运行时间时遇到的问题,这两种方法用于查找所有<=一个数的素数。当在程序中进行用户输入时。

错误的方法

#Sample input for a number 20 
#Sample output [2, 3, 5, 7, 11, 13, 17, 19]
#Total Running time = 0.634 seconds

import time

start_time = time.time()

#Method 1 to find all the prime numbers <= a Number

# Function to check whether a number is prime or not.
def prime_no(num):
if num<2:
    return False
else:
    for i in range(2, num//2+1):
        if num % i == 0:
            return False
    return True

#To print all the values <= n
def Prime_under_num(n):
    a = [2]
    if n <2:
        print("None")
    elif n==2:
        print(2)
    else:
"Neglecting all even numbers as even numbers won't be prime in order to reduce the time complexity."
        for i in range(3, n+1, 2):   
            if prime_no(i):
                a.append(i)
        print(a)


"When Method 1 is only used outputs of running time for different inputs"
#Total Running time = 2.73761 seconds #n = 100
#Total Running time = 3.14781 seconds #n = 1000
#Total Running time = 8.69278 seconds #n = 10000
#Total Running time = 18.73701 seconds #n = 100000

#Method 2 to find all the prime numbers <= a Number

def Prime_under_num(n):
    a = [2]
    if n <2:
        print("None")
    elif n==2:
        print(2)
    else:
        for i in range(3, n+1, 2):   
            if n%i ==0:
                pass
            else:
                a.append(i)
        print(a)

"When Method 2 is only used outputs of running time for different inputs"
# Total Running time = 2.75935 seconds #n = 100
# Total Running time = 2.86332 seconds #n = 1000
# Total Running time = 4.59884 seconds #n = 10000
# Total Running time = 8.55057 seconds #n = 100000

if __name__ == "__main__" :
    n = int(input())
    Prime_under_num(n)
    print("Total Running time = {:.5f} seconds".format(time.time() - start_time))

上述所有情况下获得的不同运行时间都是错误的。对于我们正在接受输入的问题,我们必须在接受输入后才开始计时。这里,用户键入输入所花费的时间也与运行时间一起计算。

正确的方法

我们必须从开头删除start_time=time.time()并将其添加到主块中。

if __name__ == "__main__" :
    n = int(input())
    start_time = time.time()
    Prime_under_num(n)
    print("Total Running time = {:.3f} seconds".format(time.time() - start_time))

因此,两种方法单独使用时的输出如下:-

# Method 1

# Total Running time = 0.00159 seconds #n = 100
# Total Running time = 0.00506 seconds #n = 1000
# Total Running time = 0.22987 seconds #n = 10000
# Total Running time = 18.55819 seconds #n = 100000

# Method 2

# Total Running time = 0.00011 seconds #n = 100
# Total Running time = 0.00118 seconds #n = 1000
# Total Running time = 0.00302 seconds #n = 10000
# Total Running time = 0.01450 seconds #n = 100000

现在我们可以看到,与错误方法相比,总运行时间有显著差异。即使方法2在两种方法中的性能优于方法1,但第一种方法(错误方法)是错误的。