Why does Python “preemptively” hang when trying to calculate a very large number?

后端 未结 2 1958
北恋
北恋 2020-12-14 14:07

I\'ve asked this question before about killing a process that uses too much memory, and I\'ve got most of a solution worked out.

However, there is one problem: calcu

2条回答
  •  忘掉有多难
    2020-12-14 15:03

    Use a function.

    It does seem that Python tries to precompute integer literals (I only have empirical evidence; if anyone has a source please let me know). This would normally be a helpful optimization, since the vast majority of literals in scripts are probably small enough to not incur noticeable delays when precomputing. To get around this, you need to make your literal be the result of a non-constant computation, like a function call with parameters.

    Example:

    import resource
    import os
    import signal
    
    def timeRanOut(n, stack):
        raise SystemExit('ran out of time!')
    signal.signal(signal.SIGXCPU, timeRanOut)
    
    soft,hard = resource.getrlimit(resource.RLIMIT_CPU)
    print(soft,hard)
    resource.setrlimit(resource.RLIMIT_CPU, (10, 100))
    
    f = lambda x=10:x**(x**x)
    y = f()
    

    This gives the expected result:

    xubuntu@xubuntu-VirtualBox:~/Desktop$ time python3 hang.py
    -1 -1
    ran out of time!
    
    real    0m10.027s
    user    0m10.005s
    sys     0m0.016s
    

提交回复
热议问题