Im trying to get a timestamp in ticks to start a periodic task with reduced jitter. To do that I get the ticks at the start of each second and upon first execution of a task I initialize a timestamp by subtracting the startTicks from the currentTicks. The problem is that this has proven very unreliable as most of the time my first task has a Timestamp of -1 Ticks aka -0.001s. This leads me to believe that the rest of them are also invalid.
void main(){
clock_t startTicks; //Ticks at the start of Second;
time_t StartSeconds, CurrentSeconds; //
time(&StartSeconds);
time(&CurrentSeconds);
// stuff ListFunctions();
for(;;){
if(CurrentSeconds != time(NULL)){ // Groundwork of iteratig over code every second
startTicks = clock();
// initializeTasks if they need to be
// reset Task availability
time(&CurrentSeconds);
}
for (int Task = 0; Task < 4; ++Task) { // initialize timestamp on first run
if(Tasks[Task].StampInitialized == 0){
Tasks[Task].TimeStamp = clock() - startTicks;
printf("%d - %d = %d", clock(), startTicks, Tasks[Task].TimeStamp);
Tasks[Task].StampInitialized = 1;
}
// wait if time stamp hasnt been crossed
printf("Start Task %d: %.3f; ", Task + 1, 1.0 *(clock() - startTicks) / CLOCKS_PER_SECOND);
// execute Task
}
}
}
The output looks like this:
> 0 - 1 = -1 Start Task 1: 0.000;
> 3 - 1 = 2 Start Task 2: 0.005;
> 8 - 1 = 7 Start Task 3: 0.008;
> 11 - 1 = 10 Start Task 4: 0.012;
CLOCKS_PER_SECOND = 1000 which is true as far as I have tested.
I couldn't find anything that explains clock() in more detail and I have a hard time believeing that it only takes MINUS 1ms to get from the start of the programm through the initialization of 4 Tasks. The initialization is nothing more than the creation of an Array for every task and sorting the content. Although apparently going from TimeStamp initializing to the task-execution (which is only writing into a variable once and 1 if question) takes between 0 and 2ms as represented by the output. I really can't think of anything that might cause this issue except some dumb logic error. However I couldnt find anything and I hope its somthing I can fix and not just weird behavior.
Im sorry if a lot of information is missing, this is my first question on any forum of any kind and english is not my mother tongue. Im open to criticism and any questions.
Thanks in advance.