0

I am running a benchmark test on a filesystem in RAM, the current test I am running takes about 0.6 seconds. To get good data I need to know exactly when the program starts and ends. The current methode give out this output: Sat May 7 19:24:46 2016, but I also need to know milliseconds. The program is executed in c++ in linux by running this command: g++ -std=c++11 2cprogram.cpp

std::time_t result = std::time(NULL);
std::cout << std::ctime(&result);
Timmy
  • 1
  • 1
  • 2

2 Answers2

1

C++11 introduced new <chrono> library. You may use high_resolution_clock from it to measure time differences and then convert it to std::duration

#include <iostream>
#include <thread>

int main() {
    auto start = std::chrono::high_resolution_clock::now();
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(600));
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end-start;
    std::cout << "Waited " << elapsed.count() << " ms\n";
}

Example is taken from cppreference.com

myaut
  • 11,174
  • 2
  • 30
  • 62
  • Tanks for fast answer. The problem is not to know how long time the program is running but when is it executed and stopped. I am running a bash script in the background that takes measurement of cpu and ram ussage every 100ms while running the filesystem test. To find the corresponding time in that data when the program starts and ends. I could do a system call for linux, because I have the command line to execute $(date +%s,%N). However this would be done within the c++ program and might give extra overhead cost. – Timmy May 07 '16 at 17:47
0

You should use clock_gettime().

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Doubtful. If it's a filesystem test, a substantial chunk of execution time will not be in this process, but in system calls. OP almost certainly needs wall time. – Lightness Races in Orbit May 07 '16 at 17:42
  • @LightnessRacesinOrbit: `clock_gettime()` can give wall time. – John Zwinck May 07 '16 at 17:50
  • @LightnessRacesinOrbit Wall time is almost always wrong, monotonic time is what you want. – o11c May 07 '16 at 17:52
  • 1
    @o11c: `clock_gettime()` can give monotonic time too. Yay. – John Zwinck May 07 '16 at 17:55
  • @JohnZwinck: Wall time is "real time", whether 1970-epoch and prone to time steps, or measured using the monotonic clock. Yes, _wall time measured by the monotonic clock_ would be best. But you suggested `std::clock`, which is CPU time _per process_, a very very different thing. – Lightness Races in Orbit May 07 '16 at 18:28
  • @LightnessRacesinOrbit: OK, I removed that part of my answer. – John Zwinck May 08 '16 at 01:10
  • 1
    @JohnZwinck: Awesome. I can get behind this now :) Perhaps consider adding some explanation of why you think that's a good function to use, to make this into a good answer. (Or don't, as the question's a duplicate anyway) – Lightness Races in Orbit May 08 '16 at 13:47