How do I get time of a Python program's execution?

后端 未结 30 2366
甜味超标
甜味超标 2020-11-22 02:20

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I\'ve looked at the timeit

30条回答
  •  忘掉有多难
    2020-11-22 03:01

    I used a very simple function to time a part of code execution:

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

    And to use it, just call it before the code to measure to retrieve function timing, and then call the function after the code with comments. The time will appear in front of the comments. For example:

    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)))
    

    Then the output will look like this:

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

提交回复
热议问题