顺序:for i in {1..1000}; do do_something $i; done
-太慢
并行:for i in {1..1000}; do do_something $i& done
-负载过多
如何并行运行命令,但每秒钟最多运行20个实例?
现在通常使用hack like for i in {1..1000}; do do_something $i& sleep 5; done
,但这不是一个好的解决方案。
更新2:将接受的答案转换为脚本:http : //vi-server.org/vi/parallel
#!/bin/bash
NUM=$1; shift
if [ -z "$NUM" ]; then
echo "Usage: parallel <number_of_tasks> command"
echo " Sets environment variable i from 1 to number_of_tasks"
echo " Defaults to 20 processes at a time, use like \"MAKEOPTS='-j5' parallel ...\" to override."
echo "Example: parallel 100 'echo \$i; sleep \`echo \$RANDOM/6553 | bc -l\`'"
exit 1
fi
export CMD="$@";
true ${MAKEOPTS:="-j20"}
cat << EOF | make -f - -s $MAKEOPTS
PHONY=jobs
jobs=\$(shell echo {1..$NUM})
all: \${jobs}
\${jobs}:
i=\$@ sh -c "\$\$CMD"
EOF
请注意,必须使用“ i =“之前的2个制表符替换8个空格才能使其正常工作。