- Aggregated Pivot Table
- Bit Shifting
- Bitwise XOR
- Calculate Tick Size
- Collapsing Dictionaries
- Graphs - Breadth First Search
- Graphs - Depth First Search
- Graphs - Detecting Cycles
- Greatest Common Divisor
- Identity Matrix
- Least Common Multiple
- Log Parser
- Nanosleep
- One Hot Encoding
- Parent Child ID Mapping
- Slippage
- Split Training and Testing Sets
- Stratified Sampling
- Symbol Column Update
- Table Indexing
- Word Count
Nanosleep
Question: Write a function 'nsleep' in C that takes in a q timespan or long argument, and puts the calling thread to sleep for that many nanoseconds.
Example
q)\s
3i
q)sleep:`sleep 2: (`nsleep;1) / load 'nsleep' from shared library (sleep.so)
q)sleep 00:00:01n
0i
q)\t sleep 1000000000
1000
q)\t sleep 00:00:01n
1000
q)\t sleep 00:00:00.100n
100
q)\t sleep 00:00:00.001n
1
q)\t sleep 00:00:01.001n
1001
/ can use sleep on multiple threads
q)\t sleep peach 00:00:01 00:00:01.001 00:00:00.001n
1001
Solution
######## sleep.c ########
// sleep.c
#include <time.h>
#include"k.h"
K nsleep(K nanos){
struct timespec t;
t.tv_sec = nanos->j / 1000000000ULL;
t.tv_nsec = nanos->j % 1000000000ULL;
return ki(nanosleep(&t, &t));
}
// generate shared object
// gcc -shared -fPIC -DKXVER=3 sleep.c -o sleep.so
######## solution.q ########
sleep:`sleep 2: (`nsleep;1) / load 'nsleep' from shared library (sleep.so)
Explanation: Use the nanosleep function located in the time module. A timespec object needs to be constructed with its second and nanosecond attribute fields correctly assigned. The 'tv_nsec' attribute is in the range of 0 to 999,999,999. To get the number of seconds from the incoming nanoseconds, int divide (divide and floor) the nanoseconds by 1 billion. To get the number of remaining nanoseconds, mod the incoming nanoseconds by 1 billion. Lastly, call the 'nanosleep' function and pass in the time object's address for both arguments and return the result as a q int.