In Python, the duration refers to the amount of time a script takes to complete a task or execute a session, among other activities. Measuring the duration in Python can be crucial during debugging, evaluation, or code enhancement. Understanding how long a function runs or determining the length of your session is vital for numerous applications. Python provides various libraries to facilitate precise timing. This article will delve into all the techniques to assess the time duration in Python, accompanied by comprehensive examples.
Let us now investigate the various techniques for evaluating the elapsed time in Python.
Strategy 1: Utilizing the time Module in Python
The time.time() function from the time module offers a straightforward and efficient method to gauge elapsed time. This function returns the total number of seconds since the epoch (January 1, 1970, 00:00:00 UTC).
Sample Code:
Python
Code Copied!
var isMobile = window.innerWidth “);
editor84051.setValue(decodedContent); // Set the default text
editor84051.clearSelection();
editor84051.setOptions({
maxLines: Infinity
});
function decodeHTML84051(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard84051() {
const code = editor84051.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “python”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output84051”).html(“
"+data+"");
jQuery(".maineditor84051 .code-editor-output").show();
jQuery("#runBtn84051 i.run-code").hide();
}
})
}
function closeoutput84051() {
var code = editor84051.getSession().getValue();
jQuery(".maineditor84051 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn84051").addEventListener("click", copyCodeToClipboard84051);
document.getElementById("runBtn84051").addEventListener("click", runCode84051);
document.getElementById("closeoutputBtn84051").addEventListener("click", closeoutput84051);
Output
Clarification: Here, the time.time() function measures the time consumed by time.sleep(3). The difference between end_time and start_time indicates the duration in the script. The time unit is seconds.
Benefits of Using time.time() in Python
```html
Relatively straightforward and user-friendly
Compatible with all operating systems
Effective for tracking extended periods.
Cons of time.time() in Python
May be influenced by adjustments to the system clock.
This method lacks high accuracy for brief time spans.
Inconsistency in multi-threaded situations.
Method 2: Utilizing the time.perf_counter() function in Python
The time.perf_counter() function in Python offers a more precise timer that remains stable even with modifications to the system clock, making it suitable for performance evaluations.
Sample:
Python
Code Copied!
Output:
Clarification: In this instance, this function in Python performs significantly better for brief intervals as it offers a high-resolution timer that remains unaffected by modifications or updates to the system clock.
Advantages of time.perf_counter() in Python
This technique provides high resolution.
Not influenced by changes to the system clock.
Ideal for short code and performance evaluations.
Disadvantages of time.perf_counter() in Python
Available only in versions above Python 3.3.
This method may also lack consistency regarding the total sampling duration and can vary on different executions.
Returns a float, making it less human-readable.
Method 3: Employing the time.process_time() function in Python
time.process_time() in Python captures the time recorded by the CPU consumed by the application, excluding any sleeping time.
Sample:
Python
Code Copied!
Output:
Explanation: This function is beneficial for evaluating CPU-intensive operations, while excluding time spent on sleeping or waiting for input/output.
Advantages of time.process_time() in Python
Quantifies the actual time utilized by the CPU.
This function also disregards I/O wait duration and sleep intervals.
Offers high consistency in CPU evaluations.
Disadvantages of time.process_time() in Python
Not the most effective method for gauging total execution period.
It may not provide precise timing hence might not be dependable.
Not particularly useful for wall-clock time benchmarking.
Method 4: Utilizing the datetime Module for Measuring Elapsed Time in Python
This specific module in Python provides datetime.now() to measure elapsed time.
Example:
Python
Code Copied!
Output:
Clarification: In this context, the date.timedelta entity is tasked with providing the time span in a format that is easily comprehensible to humans.
Advantages of datetime.now() in Python
This function presents a format that is comprehensible.
This function is beneficial for recording timestamps.
Can deliver complete timestamps encompassing both time and date.
Disadvantages of datetime.now() in Python
Lower precision in comparison to time.perf_counter()
Also less accurate, making it a questionable output. Furthermore, garbage collection may happen.
May be influenced by modifications in the system clock.
Method 5: Utilizing the timeit Module in Python
This module in Python offers a more effective and precise mechanism to gauge execution time for brief code snippets.
Example:
Python
Code Copied!
Output:
Clarification: The timeit.timeit() function executes the provided function several times, in this particular instance 1500 times, and subsequently presents the cumulative time consumed. This renders the approach more trustworthy for evaluating performance.
Advantages of timeit Module in Python
This method is optimally designed for benchmarking.
It effectively removes overhead from additional operations.
Also, it eliminates extraneous overhead from unrelated tasks.
Disadvantages of timeit Module in Python
This method may not be advantageous over extended periods.
Moreover, the outcomes exhibit variability.
It can be somewhat challenging to apply for intricate and parameterized functions.
Comparison of Time Measurement Techniques in Python
Technique
Accuracy
Utilizes System Clock
Optimal Usage Scenarios
time.time()
Low since it relies on the system clock, which lacks precision
Yes
General time tracking
time.perf_counter()
High as it employs a consistent timer, suitable for short intervals
No
Accurate benchmarking
time.process_time()
High as it measures only CPU time and disregards waiting times
No
CPU execution duration
datetime.now()
Moderate because it uses the system clock, which is preferable for everyday use
Yes
Readable logs
timeit.timeit()
Extremely high since it executes code multiple times, aiding in filtering out inconsistencies
No
Code evaluation
Practical Applications of Timing Measurement
``````html
Time Calculation in Python
In the section that follows, you will discover methods for assessing elapsed time in practical scenarios.
Example 1: Measuring the response duration for an API utilizing time.perf_counter()
Python
Code Copied!
Output
Explanation: Initially, the timer starts using time.perf_counter(), followed by making a GET request to a sample API. When the response is parsed and the requests are fulfilled, the difference will indicate the duration taken for the API call.
Example 2: Employing timeit to evaluate 2 data cleansing techniques
Python
Code Copied!
Result
Clarification: In this example, the timeit.timeit() function is executed to run both cleaning functions 1000 times. You need to provide the function name as a string and import it through the setup parameter.
Optimal Approaches to Assess Time Spent in Python
When you intend to assess elapsed time in coding, select the optimal method tailored to your accuracy needs.
For straightforward benchmarking of code snippets, utilize the timeit module.
Avoid employing time.time() for brief measurement intervals.
Be certain that external elements like background activities do not skew the findings.
Conduct the measurement several times to derive a more consistent average.
Final Thoughts
From this article, we conclude that when evaluating elapsed time in Python, various methods cater to different situations and precision demands. You can employ time.time() for basic measurements or time.perf_counter() for high-precision timing. The time.process_time() function is suitable for CPU-bound execution time, while the timeit.timeit() method is apt for benchmarking. The Python ecosystem provides an array of modules to accommodate each scenario for performance evaluation and enhancement.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.