Playing around with time based integration in C++ after reading those articles (
1,
2) Reelya linked me to a while back in this thread.
Wrote a basic program using pdcurses for graphics that counts seconds up to a hardcoded goal number. Using ctime.h for the time functions. Noticed that the program would finish in a shorter amount of time than what it would get if it counted seconds perfectly. Example, goal is 10, program finishes in 9.814s using clock_t and clock() based integration, and finishes in 9.133s using time_t and time() based integration.
Am I doing this right? It works.
Tips on improving accuracy? I'd have thought that using time_t would be the more accurate option for integration based on seconds, since time_t is tracking the number of seconds, while clock_t is clock ticks. clock_t program finishes in a closer time to the goal number than time_t though.#include <iostream>
#include "resources/pdcurses/curses.h"
#include "resources/pdcurses/curseutil.h"
#include <ctime>
using namespace std;
int main()
{
initscr(); clear(); refresh();
start_color();
init_def_color_pairs();
double total_num=0,
d_num=1; //for time_t integration
//d_num=0.001; for clock_t integration
int number=total_num;
int goal=10;
//clock_t last_time=clock(); //get current time
time_t last_time=time(0); //get current time
string status="N: ";
string goal_status="Goal: ";
char cstring[8];
while(number<goal)
{
//clock_t cur_time=clock(); //gets current time
time_t cur_time=time(0); //gets current time
//clock_t d_t=cur_time-last_time; //calculates how much time has passed since last loop
time_t d_t=cur_time-last_time; //calculates how much time has passed since last loop
if(d_t>0) //if time has passed
{
//updates data
total_num+=d_num*d_t;
//total_num+=d_num;
number=total_num;
last_time=cur_time; //refreshes data of last update time
}
//draws graphics
clear();
border('=','=','=','=','+','+','+','+');
mvaddstr(2,2,status.c_str());
printitc(number, cstring);
mvaddstr(3,2,goal_status.c_str());
printitc(goal, cstring);
move(25,80); //hides blinking console cursor off screen
refresh();
}
return 0;
}
Just realized after posting this that I didn't actually finish reading those articles and they could very well address my questions already. I kinda stopped reading halfway through the first and went and tried programming once I thought I understood enough. Gonna finish reading the articles, if anyone wants to respond feel free to.
...Of course the clock ticks are more accurate because they're a smaller unit of time, so the smaller step of time increases accuracy.
Figured it out. Got the time accuracy down to .048 seconds difference, which I'm willing to attribute to the program finishing and returning 0 at the end.