1

I am testing the time cost of opening a USB2Serial port n Centos 7.4. But I found it cost about 7ms for the first time. But it cost much more time in the next opening. If I increase the sleep time, run again, it costs more time except for the first open.

I am using usb2serial device from FTDI, the kernel driver is ftdi_sio.

Here is my code:

for (int i = 0; i < 10; i++)
{
    steady_clock::time_point start = steady_clock::now();
    int handle = open("/dev/ttyUSB0", O_RDWR| O_NONBLOCK | O_NDELAY);
    steady_clock::time_point end = steady_clock::now();
    std::cout << "Item " << i <<  ":" << " " << duration_cast<std::chrono::nanoseconds>(end-start).count()/1000000 << " ms" << endl;
    usleep(10000); // us
    close(handle);
}

The result is:

Item 0: 6 ms

Item 1: 76 ms

Item 2: 75 ms

Item 3: 75 ms

Item 4: 75 ms

Item 5: 76 ms

Item 6: 75 ms

Item 7: 75 ms

Item 8: 75 ms

Item 9: 74 ms

I just wonder why the open time becomes longer after the first time. Maybe need some other operation before close.

Anyone has met similar problem ? Or any comments? Thanks

sqiang.bi
  • 11
  • 2

1 Answers1

0

std::chrono::duration_cast returns a std::chrono::duration object.

The printf function is an old C compatibility function, and as such knows nothing about C++ objects.

In short, what you're printing is not really the duration, instead you have undefined behavior! Considering you're on Ubuntu, then you're using either GCC or Clang, both compilers which should complain about that.

If you want to print the actual duration "count" then use the count member function, preferably together with std::cout to get type-safe conversions:

std::cout << "Item " << i << ": " << duration_cast<std::chrono::nanoseconds>(e1-s1).count() << " ns\n";

Or if your compiler can handle some of the changes in the upcoming C++20 standard (which defines an operator<< overload for durations):

std::cout << "Item " << i << ": " << duration_cast<std::chrono::nanoseconds>(e1-s1) << " ns\n";

The big lesson: Don't mix C++ and old C functions. They seldom mix very well.

You might also want to consider getting a few good books to help you learn C++ properly.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621