Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีได้เวลาการทำงานของโปรแกรม Python

วัดเวลาทำงานโปรแกรมด้วย time.clock() หรือ time.time() เอกสารแนะนำสำหรับ benchmarking

ตัวอย่าง

import time

t0 = time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed:", t1 - t0)  # วินาที CPU (จุดทศนิยม)

ผลลัพธ์

Time elapsed: 0.0009403145040156798

ใช้ timeit สำหรับการวิเคราะห์สถิติ รันซ้ำหลายครั้ง รายงานเวลาที่เร็วที่สุด

ตัวอย่าง

def f(x):
    return x * x

import timeit
timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)

ผลลัพธ์

[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]