sober_phoenix's blog

By sober_phoenix, history, 4 years ago, In English

If you're using any build script to build and compile your C++ program then there's a high chance your system got frozen during a contest ( possibly because there were some infinite loop that you didn't notice ) and probably you had to restart your system . This gets very irritating during a contest . Although there's a workaround of this problem using timeout script in some system, but it's not always compatible with g++ commands . A better solution is to set the resource limit ( CPU time , virtual memory , stack size etc. ) in your program using a function : setrlimit . A general template is :

#include <sys/time.h>
#include <sys/resource.h>
int setrlimit(int resource, const struct rlimit *rlim);

A detailed description of all the terminologies can be found here. the setrlimit takes two arguments the first one (resource) specifies what sort of resource you want to set limit on (e.g RLIMIT_AS for the process's virtual memory (address space) , RLIMIT_DATA for the maximum size of the process's data segment etc. ) , And the second argument specifies the numeric value of the limit that you want to impose (it's value depends on the resource parameter that you're specifying ) . Personally, I like to impose limit on the CPU time (RLIMIT_CPU) and file size (RLIMIT_FSIZE).

Note : This function works on UNIX based system , And in order to ignore any of these limits in your final submitted program it's better to wrap this snippet around an #ifndef #endif conditional directive with ONLINE_JUDGE macro . That being said here's the minimal code snippet that I use :

#include<bits/stdc++.h>   
#ifndef ONLINE_JUDGE
#include<sys/resource.h>
#include <sys/time.h>
#endif
int main(){  
        #ifndef ONLINE_JUDGE
        /* setting up soft limit on resources */
        rlimit rlim , rlim_time ;
        if(getrlimit( RLIMIT_FSIZE , &rlim) || getrlimit(RLIMIT_CPU , &rlim_time) )  
            return 1 ; 
        rlim.rlim_cur = MAX_FILE_SIZE // maximum file size (in bytes) that your program will be able to create ; 
        rlim_time.rlim_cur = CPU_TIME // maximum allowed runtime for your program ; 
        if(setrlimit( RLIMIT_FSIZE , &rlim ) || setrlimit(RLIMIT_CPU , &rlim_time))
            return 2 ; 
        #endif
}
  • Vote: I like it
  • +25
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Will it work on Windows 10 system?