File tree Expand file tree Collapse file tree 3 files changed +45
-1
lines changed
libc-bottom-half/cloudlibc/src/libc/unistd Expand file tree Collapse file tree 3 files changed +45
-1
lines changed Original file line number Diff line number Diff line change 99int usleep (useconds_t useconds ) {
1010 struct timespec ts = {.tv_sec = useconds / 1000000 ,
1111 .tv_nsec = useconds % 1000000 * 1000 };
12- int error = clock_nanosleep (CLOCK_REALTIME , 0 , & ts , NULL );
12+ #ifdef __wasilibc_use_wasip2
13+ clockid_t clock_id = CLOCK_MONOTONIC ;
14+ #else
15+ clockid_t clock_id = CLOCK_REALTIME ;
16+ #endif
17+ int error = clock_nanosleep (clock_id , 0 , & ts , NULL );
1318 if (error != 0 ) {
1419 errno = error ;
1520 return -1 ;
Original file line number Diff line number Diff line change @@ -306,6 +306,7 @@ add_wasilibc_test(time.c)
306306add_wasilibc_test(utime.c FS)
307307add_wasilibc_test(rewinddir.c FS)
308308add_wasilibc_test(seekdir.c FS)
309+ add_wasilibc_test(usleep.c)
309310
310311if (TARGET_TRIPLE MATCHES "-threads" )
311312 add_wasilibc_test(busywait.c)
Original file line number Diff line number Diff line change 1+ #include <sys/time.h>
2+ #include <time.h>
3+ #include <errno.h>
4+ #include <stdio.h>
5+ #include <stdlib.h>
6+ #include "test.h"
7+
8+ #define TEST (c ) do { \
9+ errno = 0; \
10+ if (!(c)) \
11+ t_error("%s failed (errno = %d)\n", #c, errno); \
12+ } while(0)
13+
14+ int main (void )
15+ {
16+ // Sleep for a total of 5ms
17+ long ns_to_sleep = 5E6 ;
18+
19+ struct timespec start_time , end_time ;
20+ clock_gettime (CLOCK_MONOTONIC , & start_time );
21+ TEST (usleep (ns_to_sleep / 1000 ) == 0 );
22+ clock_gettime (CLOCK_MONOTONIC , & end_time );
23+ TEST (end_time .tv_sec - start_time .tv_sec <= 1 );
24+
25+ long nanoseconds_elapsed = (end_time .tv_sec - start_time .tv_sec ) * 1E9
26+ - start_time .tv_nsec
27+ + end_time .tv_nsec ;
28+
29+ // Test that the difference between the requested amount of sleep
30+ // and the actual elapsed time is within an acceptable margin
31+ double difference = abs (nanoseconds_elapsed - ns_to_sleep )
32+ / ns_to_sleep ;
33+
34+ // Allow the actual sleep time to be twice as much as the requested time
35+ TEST (difference >= 0 && difference <= 1 );
36+
37+ return t_status ;
38+ }
You can’t perform that action at this time.
0 commit comments