3

I need a function or way to get the UNIX epoch in seconds, much like how I can in PHP using the time function.

I can't find any method except the time() in ctime which seems to only output a formatted date, or the clock() function which has seconds but seems to always be a multiple of 1 million, nothing with any resolution.

I wish to measure execution time in a program, I just wanted to calculate the diff between start and end; how would a C++ programmer do this?

EDIT: time() and difftime only allow resolution by seconds, not ms or anything too btw.

John D.
  • 265
  • 4
  • 10

3 Answers3

2

time() should work fine, use difftime for difference of time calculations. In case you need better resolutuion, use gettimeofday.

Also, duplicate of: Calculating elapsed time in a C program in milliseconds

Community
  • 1
  • 1
Drakosha
  • 11,925
  • 4
  • 39
  • 52
2

If you want to profile get, I'd recommend using getrusage. This will allow you to track CPU time instead of wall clock time:

struct rusage ru;
getrusage(RUSAGE_SELF, &ru);

ru.ru_utime.tv_sec;  // seconds of user CPU time
ru.ru_utime.tv_usec; // microseconds of user CPU time
ru.ru_stime.tv_sec;  // seconds of system CPU time
ru.ru_stime.tv_usec; // microseconds of system CPU time
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
0

This code should work for you.

time_t epoch = time(0);


#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t time = time(0);
    cout<<time<<endl;
    system("pause");
    return 0;
}

If you have any questions, feel free to comment below.

Benjamin2002
  • 311
  • 1
  • 4
  • 13