At cpu time within a thread tallison asked if it was possible to instrument cpu usage on a per-thread basis.
I didn't know how to do this at the time but now I do--for Win32.
Not useful for him as he is on Darwin and I'm not sure that it has enough uses to be worth while making it a module, but just in case someone else comes looking to do this; here it is:
I've made no attempt at encapsulation as I don't think it is useful enough to make a stand-alone module but it has given me some ideas about how to regain access to some of win32's native threading api's in conjunction with ithreads which might lead to a useful module some day.
#! perl -slw use strict; use threads; use Thread::Queue; use Win32::API::Prototype; ApiLink( 'Kernel32', 'HANDLE GetCurrentThread(void)' ) or die $^E; ApiLink( 'Kernel32', 'BOOL GetThreadTimes( HANDLE hThread, LPFILETIME lpCreationTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime )' ) or die $^E; sub filetimeToNano{ my ( $lo, $hi ) = unpack 'V2', $_[ 0 ]; return $hi * 2**32 + $lo; } sub msFiletimeToUnix{ my $nanosecs = filetimeToNano( $_[ 0 ] ); return int( ($nanosecs - 116444736010000000) / 1E7 ); } sub threadTimesStr{ my $tHandle = GetCurrentThread( 0 ) or die $^E; my @times = map{ chr( 0 ) x 10 } 1 .. 4; GetThreadTimes( $tHandle, @times ) or die $^E; return sprintf "Started: %s\n* Ended: %s\nK. time: %s\nU. time: %s", scalar localtime( msFiletimeToUnix( $times[ 0 ] ) ), scalar localtime( msFiletimeToUnix( $times[ 1 ] ) )||'n/a', filetimeToNano( $times[ 2 ] ) /1e7, filetimeToNano( $times[ 3 ] ) /1e7; } my $Q = new Thread::Queue; sub thread { my $tid = threads->self->tid; for( 1 .. 10000 ) { my @globs = <'{a,b,c,d}'x2>; } $Q->enqueue( "$tid :\n" . threadTimesStr() ); return; } my @threads = map{ threads->new( \&thread ) } 1 .. 10; $_->join for @threads; print $Q->dequeue while $Q->pending;
In reply to Per thread cpu usage for Win32, by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |