How to do it...

We are going to create two classes that save two timestamps in a file. One timestamp indicates when an instance was created, while the other indicates when the instance was destroyed. This is useful for code profiling, to measure how much time we have spent in a function or any other code block of interest. Follow these steps:

  1. In your working directory, that is, ~/testcreate a subdirectory called returns.
  2. Use your favorite text editor to create a file called returns.cpp in the returns subdirectory.
  3. Add the first class to the returns.cpp file:
#include <system_error>

#include <unistd.h>
#include <sys/fcntl.h>
#include <time.h>

[[nodiscard]] ssize_t Write(int fd, const void* buffer,
ssize_t size) {
return ::write(fd, buffer, size);
}

class TimeSaver1 {
int fd;

public:
TimeSaver1(const char* name) {
int fd = open(name, O_RDWR|O_CREAT|O_TRUNC, 0600);
if (fd < 0) {
throw std::system_error(errno,
std::system_category(),
"Failed to open file");
}
Update();
}

~TimeSaver1() {
Update();
close(fd);
}

private:
void Update() {
time_t tm;
time(&tm);
Write(fd, &tm, sizeof(tm));
}
};
  1. Next, we add the second class:
class TimeSaver2 {
int fd;

public:
TimeSaver2(const char* name) {
fd = open(name, O_RDWR|O_CREAT|O_TRUNC, 0600);
if (fd < 0) {
throw std::system_error(errno,
std::system_category(),
"Failed to open file");
}
Update();
}

~TimeSaver2() {
Update();
if (close(fd) < 0) {
throw std::system_error(errno,
std::system_category(),
"Failed to close file");
}
}

private:
void Update() {
time_t tm = time(&tm);
int rv = Write(fd, &tm, sizeof(tm));
if (rv < 0) {
throw std::system_error(errno,
std::system_category(),
"Failed to write to file");
}
}
};
  1. The main function creates instances of both classes:
int main() {
TimeSaver1 ts1("timestamp1.bin");
TimeSaver2 ts2("timestamp2.bin");
return 0;
}
  1. Finally, we create a CMakeLists.txt file containing the build rules for our program:
cmake_minimum_required(VERSION 3.5.1)
project(returns)
add_executable(returns returns.cpp)

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

SET(CMAKE_CXX_FLAGS "--std=c++17")
set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++)
  1. You can now build and run the application. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.72.224