0

在脚本上部焦点中定义了这个全局变量

t0 = time.time() ##是全局的

和这个功能

def timestamp(t0):
... return ("[" + str(time.time()-t0)+ "] ") ## 从初始开始的时间戳

我正在尝试为脚本的每个 print() 加上时间戳

打印(时间戳(t0)+“”......随便......“”)

这有效,但是当我进入多线程时

对于范围内的 thread_id(win32-safe_os):
... p = Process(target=fonction,args=((thread_id),“test”))
... p.start()
... thread_list.append(p)

为了

def fonction(thread_id,filetodo):
... print(timestamp(t0)+"加载核心"+str(thread_id))
... print(timestamp(t0)+str(filetodo)+"在核心上"+str( thread_id))
... print(timestamp(t0)+"空闲内核"+str(thread_id))

我得到这个标准输出:

[2.70299983025] 297 jpg / 36087 个文件
[2.75] 进入多线程
[2.75] Win32 发现:2 个内核
[0.0] 加载内核 0
[0.0] 对内核 0 进行测试
[0.0] 空闲内核 0
[0.0] 加载内核 1
[ 0.0] 在核心 1 上测试
[0.0] 空闲核心 1

我可以看到我对 timestamp() 和 t0 的调用正在工作,但在 p.start() 中没有。我想知道如何(以及为什么)我需要纠正?

PS:我尝试使用 time.clock,但在 win32 中它指的是线程的开头(不是脚本)/

4

2 回答 2

2

每个进程都有一个单独的全局变量实例。如果您希望每个进程看到相同的值,则需要将该值作为参数传递给每个进程。

于 2013-08-26T14:47:09.483 回答
0

以下代码:

import time
from multiprocessing import Process

t0 = time.time() ## is global

def timestamp(t0):
    return ("[" + str(time.time()-t0)+ "] ") ## time stamping from initial start

def fonction(thread_id, filetodo):
    print(timestamp(t0)+"Load core "+str(thread_id))
    print(timestamp(t0)+str(filetodo)+" on core "+str(thread_id))
    print(timestamp(t0)+"Free core "+str(thread_id))

thread_list = []
for thread_id in range(2):
    p = Process(target=fonction, args=((thread_id),"test"))
    p.start()
    thread_list.append(p)

...我的 Linux 机器上的输出:

[0.00588583946228] Load core 0
[0.00625395774841] test on core 0
[0.00644302368164] Free core 0
[0.007572889328] Load core 1
[0.00768899917603] test on core 1
[0.00770998001099] Free core 1

所以这样就可以了。您能否发送更完整的代码片段?

于 2013-08-26T14:50:02.020 回答