#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <error.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>

#define IPU_STAT_PATH "/proc/mi_modules/mi_ipu/debug_hal/ipu_status"
#define MAX_CORE_CNT 1

static int show_utilization(int interval)
{
    FILE *fp;
    int ret;
    unsigned long long util[MAX_CORE_CNT];
    unsigned long long util_end[MAX_CORE_CNT];
    float fpercent[MAX_CORE_CNT];

    fp = fopen(IPU_STAT_PATH, "r");
    if (!fp) {
        printf("fail to open %s, error=%s\n", IPU_STAT_PATH, strerror(errno));
        return -1;
    }
    ret = fscanf(fp, "%llu", &util[0]);
    fclose(fp);
    if (ret != 1) {
        printf("fail to get util !\n");
        return -1;
    }

    while (1) {
        sleep(interval);

        fp = fopen(IPU_STAT_PATH, "r");
        if (!fp) {
            printf("fail to open %s, error=%s\n", IPU_STAT_PATH, strerror(errno));
            return -1;
        }
        ret = fscanf(fp, "%llu", &util_end[0]);
        fclose(fp);
        if (ret != 1) {
            printf("fail to get util !\n");
            return -1;
        }

        fpercent[0] = (util_end[0] - util[0])*100 / (interval*1000000.0);
        printf("core0: %.2f%%\n", fpercent[0]);
        util[0] = util_end[0];
    }
}

static void _showUsage(char *program)
{
    printf("Usage: %s [-t] time_interval \n", program);
}

int main(int argc, char *argv[])
{
    int opt, interval;

    if (argc < 2) {
        printf("usage: %s -t time_interval\n", argv[0]);
        return -1;
    }

    while ((opt = getopt(argc, argv, "t:")) != -1) {
        switch (opt) {
            case 't':
               interval = atoi(optarg);
               break;
            default:
               _showUsage(argv[0]);
               return -1;
        }
    }

    if (interval <= 0) {
        interval = 3;
    }

    show_utilization(interval);
    return 0;
}
