Showing posts with label timeanalysis. Show all posts
Showing posts with label timeanalysis. Show all posts

Tuesday, February 7, 2017

Time Functions

#include <cstdio>
#include <ctime>
#include <sys/time.h>
#include <cmath>
#include <string>

#define DEBUG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__)

// Function prototypes
std::string GetTimeString();
void PrintHexData(void *data, int size);
long timeInterval(struct timeval *start, struct timeval *end);

int main()
{
    // Sample data to be printed in hexadecimal format
    char data[] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0};
    int dataSize = sizeof(data);

    // Timing variables
    struct timeval start, end;

    // Get start time
    gettimeofday(&start, NULL);

    // Call the function to print hex data
    PrintHexData(data, dataSize);

    // Get end time
    gettimeofday(&end, NULL);

    // Calculate and print the time interval
    long interval = timeInterval(&start, &end);
    printf("******** Time Interval: %ld microseconds\n", interval);

    return 0;
}

void PrintHexData(void *data, int size)
{
    char str[100] = {0};
    int wrlen = 0;
    for (int i = 0; i < size; i++)
        wrlen += sprintf(str + wrlen, "0x%.2hhX ", ((char*)data)[i]);

    DEBUG_PRINT("%s Data: %s\n", GetTimeString().c_str(), str);
}

std::string GetTimeString()
{
    char buffer[26];
    struct timeval tv;
    gettimeofday(&tv, NULL);

    int millisec = lrint(tv.tv_usec / 1000.0);     /* Round to nearest millisec */
    if (millisec >= 1000)                          /* Allow for rounding up to nearest second */
    {
        millisec -= 1000;
        tv.tv_sec++;
    }

    struct tm* tm_info = localtime(&tv.tv_sec);
    strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);

    char str[100];
    sprintf(str, "[%s.%03d]", buffer, millisec);

    return std::string(str);
}

long timeInterval(struct timeval *start, struct timeval *end)
{
    return ((end->tv_sec - start->tv_sec) * 1000000L + end->tv_usec) - start->tv_usec;
}