Background: I want to use the system functions to get the UTC to add a time stamp. The function s getdayoftime() can help to get the epoch time (beginning as 1970-1-1) and another function localtime_r can help to change the epoch time to UTC. I write a simple program to test the stability of time getting. But the results appear the seconds jumping.
Enviroment: Ubuntu 16.04 installed in Vmware Workstation 15.1 in Win 10 (1903). The program is running in the C++.
Problem: I use matlab to analyze the time differences and the result is below:
Codes: The code is very easy.
#include <sys/time.h> #include <iostream> #include <time.h> #include <fstream> #include <unistd.h> using namespace std; int main(int argc, char **argv) { int cnt=0; ofstream fp("time.txt"); //For getting the UTC struct timeval epochTime; struct tm timenow; while(1) { //Get the UTC gettimeofday(&epochTime, NULL); localtime_r(&epochTime.tv_sec, &timenow); //Write time to txt fp<<cnt<<","<<timenow.tm_year + 1900<<"-"<<timenow.tm_mon + 1<<"-"<<timenow.tm_mday<< " "<<timenow.tm_hour<<":"<<timenow.tm_min<<":"<<timenow.tm_sec<<"."<<epochTime.tv_usec<<endl; //sleep for test usleep(10000); if(cnt > 1000) { return 1; } cout << cnt << endl; cnt +=1; } return 1; } 2 Reset to default
