用c语言写一个空跑延时程序
时间: 2023-11-27 10:03:32 浏览: 32
下面是一个简单的空跑延时程序,它使用了循环来实现延时功能:
```c
#include <stdio.h>
void delay(int milliseconds) {
long pause;
clock_t now, then;
pause = milliseconds * (CLOCKS_PER_SEC / 1000);
now = then = clock();
while ((now - then) < pause) {
now = clock();
}
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("Loop %d\n", i);
delay(1000);
}
return 0;
}
```
这个程序定义了一个 `delay` 函数,它接受一个整数参数表示延时的毫秒数。函数内部使用了 `clock` 函数来获取当前的时钟时间,并通过一个循环来等待一段时间。最后,程序在 `main` 函数中使用 `delay` 函数来实现了一个空跑延时的效果。
相关问题
int dataSizePerThread = awardIds.size() / threadNum; 这段代码可能为空 再优化一下
确实,如果`awardIds`的大小小于线程数,则会出现`dataSizePerThread`为0的情况。可以在计算`dataSizePerThread`时,加上一个最小值的限制,避免出现0的情况。代码改进后如下:
```
int threadNum = 10;
int dataSizePerThread = Math.max(1, awardIds.size() / threadNum);
List<CompletableFuture<List<TCaAwardInfo>>> futures = new ArrayList<>();
for (int i = 0; i < threadNum; i++) {
int startIndex = i * dataSizePerThread;
int endIndex = Math.min((i + 1) * dataSizePerThread, awardIds.size());
List<Long> subList = awardIds.subList(startIndex, endIndex);
CompletableFuture<List<TCaAwardInfo>> future = CompletableFuture.supplyAsync(() -> {
List<TCaAwardInfo> result = new ArrayList<>();
List<TCaAwardInfo> tCaAwardInfos = awardApiService.queryActivationCode(subList);
result.addAll(tCaAwardInfos);
return result;
}, taskExecutor);
futures.add(future);
}
List<TCaAwardInfo> activationCodeList = new ArrayList<>();
for (CompletableFuture<List<TCaAwardInfo>> future : futures) {
activationCodeList.addAll(future.join());
}
```
这样,即使`awardIds`的大小小于线程数,也能保证每个线程都有数据处理,避免了线程空跑的情况。