2

我有一个用户提交的 cpp 代码。我的数据库中也有输入和输出文件。如何在我拥有的输入和输出文件上编译和运行这个 cpp 代码。

另外,如何限制上述代码运行的运行时间和内存消耗。另外,我如何测量有多少内存以及执行上述代码需要多少时间。

编辑我在下面的黑客工作中得到了这个。现在唯一的问题是如何限制正在运行的程序的内存使用量。如果它独立于操作系统,我将不胜感激。但是,如果它对于 Windows 和 Linux 都是不可能的解决方案,我们欢迎您。

需要“超时”

    runDir = 'run\\'

    def code_file( sid )
        return "#{sid}.cpp"
    end

    def executable_file( sid )
        return "#{sid}.exe"
    end

    def input_file( sid )
        return "#{sid}.in"
    end

    def output_file( sid )
        return "#{sid}.out"
    end

    def get_complie_command_line( sid , runDir)
        return "g++ -w -O2 #{code_file(sid)} -o #{runDir}#{executable_file(sid)}"
    end

    def get_run_command_line( sid , runDir )
        return "#{runDir}#{executable_file(sid)} < #{sid}.in"
    end

    def run_submission( sid , runDir )
        begin
        timeout(5) {
            run_cmd_line = get_run_command_line( 1 , runDir)
            puts run_cmd_line
            runOutput = %x[#{run_cmd_line}]
            puts runOutput
        }
        puts "Timeout didn't occur"
        rescue Timeout::Error    
            puts "Timed out!"
        end
    end

    def compile( sid , runDir )
        #make the directory 
        %x[mkdir #{runDir}]

        #get compile command line and produce the exe
        cmd_line = get_complie_command_line( 1 , runDir)
        puts cmd_line
        compile_error = %x[#{cmd_line}].to_s.strip

        #run the code
        if compile_error.length != 0 
            puts "Compile Errors"
        else
            run_submission( 1 , runDir )
        end
    end



    compile( 1 , runDir)
4

1 回答 1

0

您可以使用您的 ruby​​ 代码创建一些运行脚本,如果您使用的是类似 *nix 的操作系统,请说 run.sh。这个脚本的上下文将是这样的:

#!/bin/bash
/path/to/timeout /path/to/your/compiled/cpp/program < /your/stdin > /your/stdout

超时程序是这个 perl 脚本https://github.com/pshved/timeout 如果它违反时间或内存限制,它将杀死您的程序。在 ruby​​ 中,您只需执行 run.sh 脚本 ( run.sh) 或类似的东西。对于 Windows,您可以使用相同的方法

于 2012-06-14T07:06:25.177 回答