Shuzheng
Shuzheng

Reputation: 14048

Increase precision of Python's time.process_time()

I want to increase the precision of Python's process_time() function.

Running the following code, I often get elapsed_time equal to 0, which is not satisfactory.

What could I do to improve precision?

t = time.process_time()
matches = search_kmp(x, p)
elapsed_time = time.process_time() - t

The purpose of the time measurements are benchmarking of algorithms.

Upvotes: 1

Views: 401

Answers (2)

Maximilian Peters
Maximilian Peters

Reputation: 31739

The only real way to improve precision is to measure multiple times and average the results. Some functions are too fast to be measured accurately. Try using timeit, https://docs.python.org/3.5/library/timeit.html

import timeit
print(timeit.timeit("search_kmp(x, p)", setup="from __main__ import search_kmp, x, p"))

Upvotes: 1

johntellsall
johntellsall

Reputation: 15180

To benchmark small bits of Python code, use the timeit module. It lets you specify how many iterations to run, compensates for overhead, and has a CLI and programmatic interface.

An example:

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.8187260627746582
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.7288308143615723
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.5858950614929199

Upvotes: 1

Related Questions