
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to get time in milliseconds using C++ on Linux?
Here we will see how to get time (the elapsed time for the program or any other kind of time).
Here we are using linux library for C++. There is a structure called timeval. This timeval stores the time in seconds, milliseconds. We can create two time for start and end, then find the difference from them.
Example
#include <sys/time.h> #include <iostream> #include <unistd.h> using namespace std; main() { struct timeval start_time, end_time; long milli_time, seconds, useconds; gettimeofday(&start_time, NULL); cout << "Enter something: "; char ch; cin >> ch; gettimeofday(&end_time, NULL); seconds = end_time.tv_sec - start_time.tv_sec; //seconds useconds = end_time.tv_usec - start_time.tv_usec; //milliseconds milli_time = ((seconds) * 1000 + useconds/1000.0); cout << "Elapsed time: " << milli_time <<" milliseconds\n"; }
Output
Enter something: h Elapsed time: 2476 milliseconds
- Related Articles
- Get time in milliseconds using Java Calendar
- How to get current time in milliseconds in Python?
- How to get Time in Milliseconds for the Given date and time in Java?
- How to get time in milliseconds since the Unix epoch in JavaScript?
- Java Program to get Milliseconds between two time instants
- How to Convert Milliseconds to Time in Excel?
- How to save time in milliseconds in MySQL?
- How to get only the file name using find command on Linux?
- Java Program to display computer time in milliseconds
- Java Program to display date and time in Milliseconds
- How to get min, seconds and milliseconds from datetime.now() in Python?
- How to get memory usage under Linux in C++
- How to get the start time of a long running Linux Process?
- Java Program to get milliseconds between dates
- How to get the current time in millisecond using JavaScript?

Advertisements