简体   繁体   中英

Not getting proper time duration in C

Let's consider a multi-sports race event like a triathlon. In this event when a person completes one activity (running, swimming, cycling etc) they immediately start a new activity after it. Suppose I have a device that continuously monitors the activity of the person. If you see the code, in "main()" function the volatile variable "activity" gets input from the device. The race was started 2 Hr before.

My aim is to find out from how long till the current moment the person is in that particular activity. Say from past 1000 seconds the person is in running activity and earlier he/she was doing "cycling" (this could be anything in the general case). Also, the point is that the end time of previous activity is the start time current activity.

The "triathlonTim()" function is called after every 1 sec continuously. When I calculate time as per my code, it's coming out to be 1 sec but actually it should be 1000 seconds. Here, time(NULL) and "stateTim" are updating continuously. "StateTim" variable must only be updated at the point when the person stops one activity and start other activity. So how do I fix it out? Any other idea or hint can also be useful to me.

#include<stdio.h>
#include<time.h>

#define CYCLING 1
#define RUNNING 2
#define SWIMMING 3 

static int state ;
static int prevState ;
int stateTim;

void triathlonTim(int activity)
{
    int activtyTimDur ;

    if(activity == 10)  
    {
        printf("doing Cycling\n\r");
        state = CYCLING;
    }
    else if(activity == 20) 
    {
        printf("doing Running\n\r");
        state = RUNNING;
    }
    else if(activity == 30)
    {
        printf("doing Swimming\n\r");
        state = SWIMMING;
    }

    if(prevState != state)
    {
        activtyTimDur = time(NULL) - stateTim;
        stateTim =time(NULL);
        printf("Activity Time Duration = %d\n\r", activtyTimDur);
    }
}

int main(void) 
{
    volatile int activity;
    while(1)
    {
        triathlonTim(activity);
        sleep(1);
    }
    return 0;
}

You need to set prevState whenever the state changes. Otherwise, every call will be treated as a state change.

    if(prevState != state)
    {
        activtyTimDur = time(NULL) - stateTim;
        stateTim =time(NULL);
        prevState = state;
        printf("Activity Time Duration = %d\n\r", activtyTimDur);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM