[Bf-python] Hashing Vectors
Campbell Barton
cbarton at metavr.com
Tue Jul 18 13:32:52 CEST 2006
Martin Poirier wrote:
> --- Joe Eagar <joeedh at gmail.com> wrote:
>
>
>> Campbell Barton wrote:
>>
>>> Hi, There are a few scripts I have that I use a
>>>
>> dict for vertex
>>
>>> locations, so as not to double up on locations as
>>>
>> an example
>>
>>> vert_dict[tuple(vertex.co)]= vertex.index
>>>
>>> It would be nicer and faster if the 2,3, or 4
>>>
>> floats could be hashed,
>>
>>> any hints as to hashing a vector and possibly a
>>>
>> matrix type?
>>
>> Well, python ints do have unlimited length. So, you
>> could simply times
>> the coordinates by a fixed amount (say, 1000) to
>> retain a reasonable
>> amount of precision, convert them to ints, then pack
>> the coordinates
>> into a giant integer (96 bits or so :D ).
>>
>> Um. that'd be:
>>
>>
>> int1 = int(x*1000.0)
>> int2 = int(x*1000.0)
>> int3 = int(x*1000.0)
>> hash = int1 + (int2 << 32) + (int3 << 64)
>>
>
>
> Errr, just make a tuple of the floats then, no need to
> mess around like that.
>
> The problem is not that they are floats, the problem
> is that vector objects are mutable.
>
> This is only a problem if you want to use vectors as
> dict keys or as part of a set.
>
> Making a tuple out of them is *the* way to solve that.
> Making vector immutable is not a viable option (due to
> how wrapped vectors currently work).
>
> Martin
>
>
Yep, at the moment Im making a tuple from them, it just seems like it
could be slow - hashing vectors directly was about 17 times faster.
So I agree that tuple() on vectors is the most correct way, but Id like
a faster way and hashing a vector based on its location seems ok..
Tested on a mesh with 663552 verts, hashing the verts and hashing the
vert locations
First test 0.27
second test 4.68
------------------------
from Blender import *
print '\n\nbench'
verts= Mesh.Get('Cube').verts
d= {}
t= sys.time()
for v in verts:
d[v]= None
print sys.time()-t
d= {}
t= sys.time()
for v in verts:
d[tuple(v.co)]= None
print sys.time()-t
-------------------------
--
Campbell J Barton
133 Hope Street
Geelong West, Victoria 3218 Australia
URL: http://www.metavr.com
e-mail: cbarton at metavr.com
phone: AU (03) 5229 0241
More information about the Bf-python
mailing list