Created
January 17, 2020 11:44
-
-
Save mfleming/c26abc925d5661a7df34737822fb5f0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Copyright 2020 Matt Fleming | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <time.h> | |
| static inline unsigned long | |
| clock_delta_now_secs(struct timespec *s) | |
| { | |
| struct timespec now; | |
| clock_gettime(CLOCK_MONOTONIC_RAW, &now); | |
| return now.tv_sec - s->tv_sec; | |
| } | |
| static inline unsigned long | |
| clock_delta_now_ns(struct timespec *s) | |
| { | |
| struct timespec now; | |
| clock_gettime(CLOCK_MONOTONIC_RAW, &now); | |
| return now.tv_nsec - s->tv_nsec; | |
| } | |
| static inline void spin(unsigned long ns) | |
| { | |
| struct timespec s; | |
| clock_gettime(CLOCK_MONOTONIC_RAW, &s); | |
| while (clock_delta_now_ns(&s) < ns) | |
| ; | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| unsigned long duration, count; | |
| struct timespec start; | |
| if (argc < 2) { | |
| fprintf(stderr, "Usage: random-syscall <duration (secs)>\n"); | |
| exit(1); | |
| } | |
| duration = strtoul(argv[1], NULL, 10); | |
| printf("Executing for %lu secs\n", duration); | |
| clock_gettime(CLOCK_MONOTONIC_RAW, &start); | |
| for (count = 0; clock_delta_now_secs(&start) < duration; count++) { | |
| struct timespec ns = { | |
| .tv_sec = 0, | |
| .tv_nsec = 10, | |
| }; | |
| if (rand() % 2) { | |
| nanosleep(&ns, NULL); | |
| } else { | |
| spin(3000); | |
| } | |
| } | |
| printf("Loop count: %lu\n", count); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment