1
#include <iostream>
#include <chrono>
#include <time.h>
#include <stdio.h>

using namespace std;
using namesapce chrono;

int main() {
  int f;
  time_t start, end;
  time (&start);
  cin >> f;
  time (&end);
  double dif = difftime (end, start);
  printf ("Elapsed time is %.2lf seconds.", dif );
}

Hello everyone, I am currently working on a C++ assignment and I am essentially required to have the user input something within 10 seconds. I managed to find out how to count the time by the second but I need it to be by milliseconds because I have to find out how many milliseconds above 10 seconds was elapsed. I am not that experienced with C++ and would very much appreciate any suggestions that may help steer me in the right direction. Thanks a lot

4

3 Answers 3

5

in C++11 and more recent Standard revisions:

#include <chrono>
using namespace std::chrono;

auto start = high_resolution_clock::now();
  // something to measure
auto end = high_resolution_clock::now();
duration<double> diff = end - start; // this is in ticks
milliseconds d = duration_cast<milliseconds>(diff); // ticks to time

std::cout << diff.count() << "s\n";
std::cout << d.count() << "ms\n";

in previous to that :

<sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

Also you can use this simple snippet code to benchmark your code blocks :

using namespace std::chrono;

class benchmark {
  public:
  time_point<high_resolution_clock>  t0, t1;
  unsigned int *d;
  benchmark(unsigned int *res) : d(res) { 
                 t0 = high_resolution_clock::now();
  }
  ~benchmark() { t1 = high_resolution_clock::now();
                  milliseconds dur = duration_cast<milliseconds>(t1 - t0);
                  *d = dur.count();
  }
};

// one way to use it can be :
#define BENCH(TITLE,CODEBLOCK) \
  unsigned int __time__##__LINE__ = 0;  \
  { benchmark bench(&__time__##__LINE__); \
      CODEBLOCK \
  } \
  printf("%s took %dms\n",(TITLE),__time__##__LINE__);


int main(void) {
  BENCH("TITLE",{
    for(int n = 0; n < testcount; n++ )
      int a = n % 3;
  });
  return 0;
}
4

Something along these lines...

#include <iostream>
#include <chrono>
auto start(std::chrono::high_resolution_clock::now());

// Code...

auto end(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>(end - start));
std::cout << "Duration: " << duration.count() << " ms\n";
0

The following complete program shows how this can be done, by using the std::chrono facilities added in C++11:

#include <iostream>
#include <chrono>
#include <thread>

int main(int argc, char *argv[]) {
    // Check args.

    if (argc != 2) {
        std::cerr << "Usage: testprog <sleepTime>" << std::endl;
        return 1;
    }

    // Create a millisecond sleep time from argument.

    auto sleepTime = strtoul(argv[1], nullptr, 10);
    sleepTime = sleepTime * 1234 + 1000;
    std::cout << "Given '" << argv[1] <<
        "', should sleep for about " << sleepTime <<
        "ms ... " << std::flush;

    // Get the start time, then wait for a bit.

    auto startTime(std::chrono::high_resolution_clock::now());

    std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));

    // Get end time, work out and print duration.

    auto endTime(std::chrono::high_resolution_clock::now());
    auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
        (endTime - startTime));
    std::cout << "that took " << duration.count() << "ms." << std::endl;
}

Running this with the following bash test command:

for i in {0..10} ; do ./testprog $i ; done

gives you the results you would expect:

Given '0', should sleep for about 1000ms ... that took 1000ms.
Given '1', should sleep for about 2234ms ... that took 2235ms.
Given '2', should sleep for about 3468ms ... that took 3469ms.
Given '3', should sleep for about 4702ms ... that took 4703ms.
Given '4', should sleep for about 5936ms ... that took 5937ms.
Given '5', should sleep for about 7170ms ... that took 7170ms.
Given '6', should sleep for about 8404ms ... that took 8404ms.
Given '7', should sleep for about 9638ms ... that took 9638ms.
Given '8', should sleep for about 10872ms ... that took 10872ms.
Given '9', should sleep for about 12106ms ... that took 12106ms.
Given '10', should sleep for about 13340ms ... that took 13340ms.

The important lines in that code are really just the ones that get the start and end time-points then work out the duration between them. They can be boiled down to:

#include <chrono>

auto startTime(std::chrono::high_resolution_clock::now());

// Do whatever you want to time.

auto endTime(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
    (endTime - startTime));
auto elapsedMs = duration.count();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.