0

我想测量每秒 execl 调用的数量,但我的脚本在第一次迭代后终止,因为 execl 内置了一个 leave 函数!

我想知道如何返回到我的脚本或找到一种计算方法:

t_end = time.time() + 60
counter = 0
while time.time() < t_end:
    def execlNum():
        os.execl('script.py' 'script.py', '0')

    execlNum()
    counter = counter+1
print counter/60
4

2 回答 2

2

由于exec将当前可执行映像替换为您指定的映像,因此您不能在循环中执行此操作 - 您可以说execl实际上永远不会返回(当它成功时),因为您当前的代码不再存在。

如果要测量execl每秒可以执行的操作数,可以执行以下操作:

#!/usr/bin/env python2
import time
import sys
import subprocess
import os
# duration of our benchmark
duration = 10
# time limit
limit = time.time() + duration
count = 0
# if we are in the "execl-ed process", take the arguments from the command line
if len(sys.argv)==3:
    limit = float(sys.argv[1])
    # increment the counter
    count = int(sys.argv[2])+1
# if we have time, do another execl (passing the incremented counter)
if time.time()<limit:
    os.execl('execpersec.py', 'execpersec.py', str(limit), str(count))

# if we get here, it means that the 10 seconds have expired; print
# how many exec we managed to do
print count/float(duration), "exec/sec"

但请记住,这不仅仅是对实际exec时间进行基准测试(根据操作系统的需要),更像是对 Python 启动时间(以及编译此脚本所需的时间)的基准测试;在我的机器上,这个脚本输出 58.8 exec/sec,而它直接的 C 翻译(见下文)产生 1484.2 exec/sec。

#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int duration = 10;

double mytime() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec*1E-6;
}

int main(int argc, char *argv[]) {
    const double duration = 10;
    double limit = mytime() + duration;
    long count = 0;
    if(argc==3) {
        limit = atof(argv[1]);
        count = atol(argv[2])+1;
    }
    if(mytime()<limit) {
        char buf_limit[256], buf_count[256];
        sprintf(buf_limit, "%f", limit);
        sprintf(buf_count, "%ld", count);
        execl("./execpersec.x", "./execpersec.x", buf_limit, buf_count, NULL);
    }
    printf("%f exec/sec\n", count/duration);
    return 0;
}
于 2015-11-25T22:25:19.277 回答
0

您对execl()通话做出了完全错误的假设。这个系统调用没有任何“内置的离开函数”,但它有效地用从该函数的第一个参数指向的文件加载的新可执行代码替换当前进程。

所以,简短的回答是你不能

你需要以新的方式重新定义你的问题。

于 2015-11-25T21:37:02.437 回答