假设我有一个程序在给定的时间内运行(比方说,三秒钟).我想运行这个程序,使其运行速度慢n倍(在命令行中指定).如何通过(或更好,没有)更改程序来实现它?
请注意,最后添加睡眠不是解决方案.该程序必须运行较慢,不要在前三秒内全速运行,然后在剩余时间内不执行任何操作.另外,在unix下使用"nice"也不是一个好的解决方案.如果其他进程需要处理器,它将运行得更慢,但如果同时没有任何处理器要求,则全速运行.
这是一个好奇心的问题.没有什么可以做的与之相关.事实是,我记得15到20年前的游戏太快而无法在新处理器上播放,因为它们与处理器时钟同步.你不得不关掉涡轮增压器.
我们假设该程序是一个C编译程序.
我在我的linux盒子上写了一个简单的例子,如何使用SIGSTOP和SIGCONT信号减慢子进程:
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
void dosomething(void){
static volatile unsigned char buffer[1000000];
for(unsigned i=0;i<1000;i++) for(unsigned j=0;j<sizeof(buffer);buffer[j++]=i){;}
}
#define RUN 1
#define WAIT 1
int main(void){
int delay=0, status, pid = fork();
if( !pid ){ kill(getpid(),SIGSTOP); dosomething(); return 0; }
do{
waitpid( pid, &status, WUNTRACED | WCONTINUED );
if( WIFSTOPPED (status) ){ sleep(delay); kill(pid,SIGCONT); }
if( WIFCONTINUED(status) && WAIT ){ sleep(RUN ); kill(pid,SIGSTOP); }
delay=WAIT;
}while( !WIFEXITED(status) && !WIFSIGNALED (status) );
}
Run Code Online (Sandbox Code Playgroud)
当WAIT为零时没有减速,否则在每秒之后RUN父母将孩子停止WAIT几秒钟.
运行时结果:
RUN=1 WAIT=0
---------------
real 3.905s
user 3.704s
sys 0.012s
RUN=1 WAIT=1
---------------
real 9.061s
user 3.640s
sys 0.016s
RUN=1 WAIT=2
---------------
real 13.027s
user 3.372s
sys 0.032s
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4199 次 |
| 最近记录: |