0

I am reading a nano second value and want to store it in a specific variable, so that I wont loss data. Could someone tell me what could be the data type ??

example :

struct timespec ts;
getrawmonotonic(&ts);
end_time = timespec_to_ns(&ts);

what could be the data type for end_time ??

3 Answers3

3

In C++, this would be std::chrono::nanoseconds. For example, to find the length of (wall-)time taken to execute some code, you could write:

auto start = std::chrono::system_clock.now();

//do some things
//...

auto end = std::chrono::system_clock.now();
std::chrono::nanoseconds nanoseconds_taken =
    duration_cast<std::chrono::nanoseconds>(end - start);
std::cout << "Took: " << nanoseconds_taken.count() << " nanoseconds\n";
Mankarse
  • 39,818
  • 11
  • 97
  • 141
0

The definition of timespec_to_ns looks like this:

/**
 * timespec_to_ns - Convert timespec to nanoseconds
 * @ts:         pointer to the timespec variable to be converted
 *
 * Returns the scalar nanosecond representation of the timespec
 * parameter.
 */
static inline s64 timespec_to_ns(const struct timespec *ts)
{
        return ((s64) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
}

So you should store it in a 64-bit integer.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

This really depends on the exact specification of timespec_to_ns.

For linux, the type is s64. On your own system, you should be able to determine the type by looking in the header that declares timespec_to_ns.

In the general case (for C++ only), you can use auto to automatically deduce the correct return type:

struct timespec ts;
auto end_time = timespec_to_ns(&ts);

//Convert to milliseconds:
auto millis = end_time/1000000.
Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • how to convert nanosecond value to millisecond ?? – user3615655 May 12 '14 at 11:49
  • Divide by `1000000` (perhaps after converting to a floating-point type). – Mankarse May 12 '14 at 11:51
  • how to convert that into floating point ?? which data type should I use to store the value after converting it ?? could you give a example ?? – user3615655 May 12 '14 at 11:55
  • @user3615655: I've added an example. If you remove the `.` after `1000000.`, it will divide by an integer instead and you will get an integral result. – Mankarse May 12 '14 at 11:58
  • uint64_t is same as double ?? – user3615655 May 12 '14 at 12:12
  • @user3615655: I'd recommend you read a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on c++. These are very basic questions. At the very least, have a look through the [language reference on cppreference.com](http://en.cppreference.com/w/cpp/language). – Mankarse May 12 '14 at 12:15