pax_global_header00006660000000000000000000000064136125766350014530gustar00rootroot0000000000000052 comment=526acc4d2dd0f8949dfd53fa1ff015307c970899 parmap-1.1.1/000077500000000000000000000000001361257663500130105ustar00rootroot00000000000000parmap-1.1.1/.gitignore000066400000000000000000000000461361257663500150000ustar00rootroot00000000000000log* *~ _build .merlin parmap.install parmap-1.1.1/AUTHORS000066400000000000000000000013221361257663500140560ustar00rootroot00000000000000This code started as a two day exercise done at Irill in July 2011, by Marco Danelutto and Roberto Di Cosmo , that produced the architecture now contained in simplemapper. It has evolved significantly after, and it now contains a particularly efficient version of the map code on float arrays, incorporating ideas from Paul Vernaza , and that works thanks to smart code and significant insight from Jerome Vouillon . Pietro Abate provided autoconf and ocamlbuild support. Detailed contributor history is contained in the git repository available at https://github.com/rdicosmo/parmap parmap-1.1.1/CHANGES000066400000000000000000000021331361257663500140020ustar00rootroot000000000000002020/01/23 (RDC) Integrated major rewriting of the build system, moving to dune; dropped compatibility with pre-4.02 OCaml versions. 2011/11/30 (RDC) Version 0.9.8 contains the following major new features w.r.t. 0.9.4 - a chunksize parameter can be used to control the granularity of the parallelism: each worker will handle a series of chunks of this size and ask for them when ready, thus allowing the system to achieve automatic load balancing - very specialised versions of the map function are now available for arrays and float arrays, allowing to obtain significant speed-up even on relatively light computations - autoconf and ocamlbuild harness should simplify compilation and installation. 2011/08/30 (RDC) internally convert lists to array to avoid quadratic penalty in execution time on long lists, thanks to Paul Vernaza for pointing out this issue; added 'a sequence type to allow using efficiently the library both with lists and arrays. parmap-1.1.1/LICENSE000066400000000000000000000635311361257663500140250ustar00rootroot00000000000000The Library is distributed under the terms of the GNU Library General Public License version 2 (included below), with a special exception to section 6, as detailed below. As a special exception to the GNU Library General Public License, you may link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Library General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library as distributed by the authors, or a modified version of the Library that is distributed under the conditions defined in clause 2 of the GNU Library General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Library General Public License. ---------------------------------------------------------------------- GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! parmap-1.1.1/Makefile000066400000000000000000000006671361257663500144610ustar00rootroot00000000000000PREFIX_ARG := $(if $(PREFIX),--prefix $(PREFIX),) LIBDIR_ARG := $(if $(LIBDIR),--libdir $(LIBDIR),) DESTDIR_ARG := $(if $(DESTDIR),--destdir $(DESTDIR),) INSTALL_ARGS := $(PREFIX_ARG) $(LIBDIR_ARG) $(DESTDIR_ARG) DUNE_ARGS = DUNE = dune default: $(DUNE) build @install $(DUNE_ARGS) install: $(DUNE) install $(INSTALL_ARGS) $(DUNE_ARGS) test: $(DUNE) runtest $(DUNE_ARGS) clean: $(DUNE) clean doc: $(DUNE) build @doc $(DUNE_ARGS) parmap-1.1.1/README.md000066400000000000000000000144461361257663500143000ustar00rootroot00000000000000# Parmap in a nutshell Parmap is a minimalistic library allowing to exploit multicore architecture for OCaml programs with minimal modifications: if you want to use your many cores to accelerate an operation which happens to be a map, fold or map/fold (map-reduce), just use Parmap's `parmap`, `parfold` and `parmapfold` primitives in place of the standard `List.map` and friends, and specify the number of subprocesses to use by the optional parameter `~ncores`. See the `example` directory for a couple of running programs. ## DO'S and DONT'S Parmap is *not* meant to be a replacement for a full fledged implementation of parallelism skeletons (map, reduce, pipe, and the many others described in the scientific literature since the end of the 1980's, much earlier than the specific implementation by Google engineers that popularised them). It is meant, instead, to allow you to quickly leverage the idle processing power of your extra cores, when handling some heavy computational load. The principle of parmap is very simple: when you call one of the three available primitives, map, fold, and mapfold , your OCaml sequential program forks in n subprocesses (you choose the n), and each subprocess performs the computation on the 1/n of the data, in chunks of a size you can choose, returning the results through a shared memory area to the parent process, that resumes execution once all the children have terminated, and the data has been recollected. You *need* to run your program *on a single multicore machine*; repeat after me: `Parmap` _is not meant_ to run on a cluster, see one of the many available (re)implementations of the map-reduce schema for that. By forking the parent process on a single machine, the children get access, for free, to all the data structures already built, even the imperative ones, and as far as your computation inside the map/fold does not produce side effects that need to be preserved, the final result will be the same as performing the sequential operation, the only difference is that you might get it faster. The OCaml code is reasonably simple and only marginally relies on external C libraries: most of the magic is done by your operating system's fork and memory mapping mechanisms. One could gain some speed by implementing a marshal/unmarshal operation directly on bigarrays, but we did not do this yet. Of course, if you happen to have open channels, or files, or other connections that should only be used by the parent process, your program may behave in a very wierd way: as an example, *do not* open a graphic window before calling a Parmap primitive, and *do not* use this library if your program is multi-threaded! ## Pinning processes to physical CPUs To obtain maximum speed, Parmap tries to pin the worker processes to a CPU, using the scheduler affinity interface that is available in recent Linux kernels. Similar functionality may be obtained on different platforms using slightly different API. Contributions are welcome to support those other APIs, just make sure that you use autoconf properly. ## Using Parmap with Ocamlnat You can use Parmap in a native toplevel (it may be quite useful if you use the native toplevel to perform fast interactive computations), but remember that you need to load the `.cmxs` modules in it; an example is given in `example/topnat.ml` ## Preservation of output order in Parmap If the number of chunks is equal to the number of cores, it is easy to preserve the order of the elements of the sequence passed to the map/fold operations, so the result will be a list with the same order as if the sequential function would be applied to the input. This is what the `parmap`, `parmafold` and `parfold` functions do when the chunksize argument is not used. If the user specifies a chunksize that is different from the number of cores, there is no general way to preserve the ordering, so the result of calling `Parmap.parmap f l` are not necessarily in the same order as `List.map f l`. In general, using little chunksize helps in balancing the load among the workers, and provides better speed, at the price of losing the ordering: there is a tradeoff, and it is up to the user to choose the solution that better suits him/her. ## Fast map on arrays and on float arrays Visiting an array is much faster than visiting a list, and conversion of an array to and from a list is expensive, on large data structures, so we provide a specialised version of map on arrays, that beaves exactly like parmap. We also provide a highly optimised specialised parmap version that is targeted to float arrays, `array_float_parmap`, that allows you to perform parallel computation on very large float arrays efficiently, without the boxing/unboxing overhead introduced by the other primitives, including `array_parmap`. To understand the efficiency issues involved in the case of large arrays of float, here is a short summary of the steps that any implementation of a parallel map function must perform. 1. create a float array to hold the result of the computation. This operation is expensive: on an Intel i7, creating a 10M float array takes 50 milliseconds ```ocaml ocamlnat Objective Caml version 3.12.0 - native toplevel # #load "unix.cmxs";; # let d = Unix.gettimeofday() in ignore(Array.create 10000000 0.); Unix.gettimeofday() -. d;; - : float = 0.0501301288604736328 ``` 2. create a shared memory area , 3. possibly copy the result array to the shared memory area, 4. perform the computation in the children writing the result in the shared memory area, 5. possibly copy the result back to the OCaml array. All implementations need to do 1, 2 and 4; steps 3 and/or 5 may be omitted depending on what the user wants to do with the result. The `array_float_parmap` performs steps 1, 2, 4 and 5. It is possible to share steps 1 and 2 among subsequent calls to the parallel function by preallocating the result array and the shared memory buffer, and passing them as optional parameters to the `array_float_parmap` function: this may save a significant amount of time if the array is very large. ## Install ### With opam ``` opam install parmap ``` ### From source ``` make make install make test ``` parmap-1.1.1/config/000077500000000000000000000000001361257663500142555ustar00rootroot00000000000000parmap-1.1.1/config/discover.ml000066400000000000000000000025101361257663500164230ustar00rootroot00000000000000module C = Configurator.V1 let sched_setaffinity_code = {| #define _GNU_SOURCE #include int main() { cpu_set_t cpus; return sched_setaffinity(0, sizeof(cpu_set_t), &cpus); } |} let thread_policy_set_code = {| #include #include int main() { thread_affinity_policy_data_t affinityData; return thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY, &affinityData, THREAD_AFFINITY_POLICY_COUNT); } |} let int_of_bool b = if b then 1 else 0 let () = C.main ~name:"parmap" (fun c -> let ml_file = "parmap_compat.ml" in let pre_406 = [ "let map_file = Bigarray.Genarray.map_file" ] in let ml_code = match C.ocaml_config_var_exn c "version" with | "4.02.3" -> pre_406 | "4.03.0" -> pre_406 | "4.04.0" -> pre_406 | "4.04.1" -> pre_406 | "4.04.2" -> pre_406 | "4.05.0" -> pre_406 | _ -> [ "let map_file = Unix.map_file" ] in C.Flags.write_lines ml_file ml_code ; let has_sched_setaffinity = C.c_test c sched_setaffinity_code in let has_thread_policy_set = C.c_test c thread_policy_set_code in C.C_define.gen_header_file c ~fname:"setcore_stubs.h" [ "HAVE_DECL_SCHED_SETAFFINITY", Int (int_of_bool has_sched_setaffinity) ; "HAVE_MACH_THREAD_POLICY_H", Int (int_of_bool has_thread_policy_set) ] ; ); parmap-1.1.1/config/dune000066400000000000000000000000751361257663500151350ustar00rootroot00000000000000(executable (name discover) (libraries dune.configurator)) parmap-1.1.1/dune-project000066400000000000000000000020171361257663500153320ustar00rootroot00000000000000(lang dune 1.10) (name parmap) (generate_opam_files true) (license "LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception") (authors "Roberto Di Cosmo ") (maintainers "Roberto Di Cosmo ") (homepage "https://github.com/rdicosmo/parmap") (bug_reports "https://github.com/rdicosmo/parmap/issues") (source (github rdicosmo/parmap)) (package (name parmap) (synopsis "Minimalistic library allowing to exploit multicore architecture") (description "Parmap is a minimalistic library allowing to exploit multicore\narchitecture for OCaml programs with minimal modifications: if you\nwant to use your many cores to accelerate an operation which happens\nto be a map, fold or map/fold (map-reduce), just use Parmap\226\128\153s parmap,\nparfold and parmapfold primitives in place of the standard List.map\nand friends, and specify the number of subprocesses to use by the\noptional parameter ~ncores.") (depends dune dune-configurator base-bigarray base-unix (ocaml (>= 4.02.3)))) parmap-1.1.1/example/000077500000000000000000000000001361257663500144435ustar00rootroot00000000000000parmap-1.1.1/example/LICENCE000066400000000000000000000432541361257663500154400ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. parmap-1.1.1/example/dune000066400000000000000000000004621361257663500153230ustar00rootroot00000000000000(executable (name mandels) (modules mandels) (flags (:standard -w -3-27)) (libraries parmap graphics unix bigarray)) ;(executable ; (name mandels_sdl) ; (public_name ocaml-parmap-mandels_sdl) ; (modules mandels_sdl) ; (flags ; (:standard -w -3-27)) ; (libraries parmap graphics unix bigarray sdl)) parmap-1.1.1/example/mandels.ml000066400000000000000000000146341361257663500164300ustar00rootroot00000000000000(**************************************************************************) (* Sample use of ParMap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Marco Danelutto and Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) (* for the toplevel #use "topfind";; #require "graphics";; #require "parmap";; *) open Graphics;; let n = ref 1000;; (* the size of the square screen windows in pixels *) let res = ref 1000;; (* the resolution: maximum number of iterations allowed *) (* scale factor and offset of the picture *) let scale = ref 1.;; let ofx = ref 0.;; let ofy = ref 0.;; (* convert an integer in the range 0..res into a screen color *) let color_of c res = truncate (((float c)/.(float res))*.(float Graphics.white));; (* compute the color of a pixel by iterating z_n+1=z_n^2+c *) (* j,k are the pixel coordinates *) let pixel (j,k,n) = let zr = ref 0.0 in let zi = ref 0.0 in let cr = ref 0.0 in let ci = ref 0.0 in let zrs = ref 0.0 in let zis = ref 0.0 in let d = ref (2.0 /. ((float n) -. 1.0)) in let colour = Array.make n (Graphics.black) in for s = 0 to (n-1) do let j1 = ref (((float j.(s)) +. !ofx) /. !scale) in let k1 = ref (((float k) +. !ofy) /. !scale) in begin zr := !j1 *. !d -. 1.0; zi := !k1 *. !d -. 1.0; cr := !zr; ci := !zi; zrs := 0.0; zis := 0.0; for i=0 to (!res-1) do begin if(not((!zrs +. !zis) > 4.0)) then begin zrs := !zr *. !zr; zis := !zi *. !zi; zi := 2.0 *. !zr *. !zi +. !ci; zr := !zrs -. !zis +. !cr; Array.set colour s (color_of i !res); end; end done end done; (colour,k);; (* draw a line on the screen using fast image functions *) let show_a_result r = match r with (col,j) -> draw_image (make_image [| col |]) 0 j;; (* generate the initial configuration *) let initsegm n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n ;; let tasks = let ini = Array.make !n 0 in let iniv = for i=0 to (!n-1) do Array.set ini i i done; ini in List.map (fun seed -> (iniv,seed,!n)) (initsegm !n) ;; let draw res = List.iter show_a_result res;; (*** fork compute back-end *) type signal = Compute of int*float*float*float*int*int (* resolution, ofx, ofy, scale, ncores, chunksize *) | Exit (* finished computation *) ;; let cmdpipe_rd,cmdpipe_wr=Unix.pipe ();; let respipe_rd,respipe_wr=Unix.pipe ();; match Unix.fork() with 0 -> begin (* compute back-end *) Unix.close cmdpipe_wr; Unix.close respipe_rd; let ic = Unix.in_channel_of_descr cmdpipe_rd in let oc = Unix.out_channel_of_descr respipe_wr in while true do let msg = try Marshal.from_channel ic with _ -> exit 0 in match msg with Compute (res',ofx',ofy',scale',nc',cs') -> Printf.eprintf "Got task...\n%!"; res:=res';ofx:=ofx';ofy:=ofy';scale:=scale'; let m = Parmap.parmap ~ncores:nc' ~chunksize: cs' pixel (Parmap.L tasks) in (Marshal.to_channel oc m []; flush oc) | Exit -> exit 0 done end | -1 -> Printf.eprintf "fork error: pid %d" (Unix.getpid()); | pid -> () ;; (*** the main continues here *) Unix.close cmdpipe_rd;; Unix.close respipe_wr;; let out,read = let ic = Unix.in_channel_of_descr respipe_rd in let oc = Unix.out_channel_of_descr cmdpipe_wr in (fun m -> Marshal.to_channel oc m []; flush oc), (fun () -> Marshal.from_channel ic) ;; (* compute and draw *) let compute () = let _ = out (Compute (!res,!ofx,!ofy,!scale,4,1)) in read();; let redraw () = Printf.eprintf "Computing...%!"; draw(compute()); Printf.eprintf "done.\n%!";; (* event loop for zooming into the picture *) let rezoom x y w = let deltas = ((float !n)/.(float w)) in ofx := (!ofx +. (float x)) *. deltas; ofy := (!ofy +. (float y)) *. deltas; scale := !scale *. deltas; redraw();; let reset () = scale:=1.; ofx:=0.; ofy:=0.;redraw();; let refine () = res:=!res*2; redraw ();; let unrefine () = res:=!res/2; redraw ();; let zoom_in () = rezoom (!n/4) (!n/4) (!n/2);; let zoom_out () = rezoom (-(!n/2)) (-(!n/2)) (!n*2);; let dumpnum = ref 0;; let dump () = Printf.eprintf "Dumping image taken at ofx: %f ofy: %f scale: %f\n%!" !ofx !ofy !scale; let img = Graphics.dump_image (Graphics.get_image 0 0 !n !n) in let oc = open_out (Printf.sprintf "mandels.image.dump.%04d" !dumpnum) in Marshal.to_channel oc img []; dumpnum:=!dumpnum+1; close_out oc;; (* encode state machine here *) let rec init () = Printf.eprintf "Init...\n%!"; let s = wait_next_event [Button_down; Key_pressed] in if s.button then track_rect s.mouse_x s.mouse_y None else if s.keypressed then match s.key with '+' -> let _ = zoom_in() in init () | '-' -> let _ = zoom_out() in init () | 'r' -> let _ = refine () in init () | 'u' -> let _ = unrefine () in init () | 'c' -> let _ = reset() in init () | 'd' -> let _ = dump() in init () | 'q' -> close_graph() | _ -> init () and track_rect x y oldimg = Printf.eprintf "Rect...\n%!"; let s = wait_next_event [Button_up; Mouse_motion] in let x'=s.mouse_x and y'=s.mouse_y in let bx,by,w,h = (min x x'), (min y y'), (abs (x'-x)), (abs (y'-y)) in if s.button then begin (* restore image if we are in the loop *) (match oldimg with None -> () | Some (i,x,y) -> draw_image i x y); if w>0 & h>0 then let i = get_image bx by w h in (* draw the border _inside_ the area *) draw_rect bx by (w-1) (h-1); track_rect x y (Some(i,bx,by)) else track_rect x y oldimg end else (rezoom bx by (min w h); init()) ;; (*** Open the main graphics window and run the event loop *) Graphics.set_window_title "Mandelbrot";; Graphics.open_graph (" "^(string_of_int !n)^"x"^(string_of_int !n));; redraw();; init() parmap-1.1.1/example/mandels_sdl.ml000066400000000000000000000203371361257663500172670ustar00rootroot00000000000000(**************************************************************************) (* Sample use of ParMap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Marco Danelutto and Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) (* for the toplevel #use "topfind";; #require "graphics";; #require "parmap";; #require "sdl";; *) let ncores = ref 4;; (* how many core we use *) let chunksize = ref 1;; (* granularity *) let n = ref 1000;; (* the size of the square screen windows in pixels *) let res = ref 1000;; (* the resolution: maximum number of iterations allowed *) (* scale factor and offset of the picture *) let scale = ref 1.;; let ofx = ref 0.;; let ofy = ref 0.;; (* convert an integer in the range 0..res into a screen color *) let color_of c res = truncate (((float c)/.(float res))*.(float Graphics.white));; (* compute the color of a pixel by iterating z_n+1=z_n^2+c *) (* j,k are the pixel coordinates *) let pixel (j,k,n) = let zr = ref 0.0 in let zi = ref 0.0 in let cr = ref 0.0 in let ci = ref 0.0 in let zrs = ref 0.0 in let zis = ref 0.0 in let d = ref (2.0 /. ((float n) -. 1.0)) in let colour = Array.make n (Graphics.black) in for s = 0 to (n-1) do let j1 = ref (((float j.(s)) +. !ofx) /. !scale) in let k1 = ref (((float k) +. !ofy) /. !scale) in begin zr := !j1 *. !d -. 1.0; zi := !k1 *. !d -. 1.0; cr := !zr; ci := !zi; zrs := 0.0; zis := 0.0; for i=0 to (!res-1) do begin if(not((!zrs +. !zis) > 4.0)) then begin zrs := !zr *. !zr; zis := !zi *. !zi; zi := 2.0 *. !zr *. !zi +. !ci; zr := !zrs -. !zis +. !cr; Array.set colour s (color_of i !res); end; end done end done; (colour,k);; (* generate the initial configuration *) let initsegm n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n ;; let tasks = let ini = Array.make !n 0 in let iniv = for i=0 to (!n-1) do Array.set ini i i done; ini in List.map (fun seed -> (iniv,seed,!n)) (initsegm !n) ;; (* draw a line on the screen using fast image functions *) let unpack_color n = let r = (n land 0xff0000) lsr 16 and g = (n land 0x00ff00) lsr 8 and b = n land 0xff in (r,g,b) ;; let draw_line screen (col,j) = Array.iteri (fun i c -> Sdlvideo.put_pixel_color screen i j (unpack_color c)) col;; let draw screen res = List.iter (fun c -> draw_line screen c) res;; (* compute *) let compute () = let d = Unix.gettimeofday() in let res = if !ncores > 1 then Parmap.parmap ~ncores: !ncores ~chunksize: !chunksize pixel (Parmap.L tasks) else List.map pixel tasks in Printf.eprintf " [time: %f] %!" (Unix.gettimeofday() -. d); res ;; (*** Open the main graphics window and run the event loop *) open Sdlevent;; open Sdlkey;; open Sdlvideo;; Sdl.init [`VIDEO];; let (bpp, w, h) = (24, !n, !n);; let screen = Sdlvideo.set_video_mode ~w ~h ~bpp [];; (* two pixel deep surfaces for drawing and saving area borders *) (* one pixel for each border: two horizontal and two vertical *) let shadowh = Sdlvideo.create_RGB_surface_format screen [`SWSURFACE] ~w ~h:2;; let shadowv = Sdlvideo.create_RGB_surface_format screen [`SWSURFACE] ~w:2 ~h;; (* one pixel deep white surfaces for drawing area borders *) let whiteh = let surf = Sdlvideo.create_RGB_surface_format screen [`SWSURFACE] ~w ~h:1 in for i = 0 to w-1 do Sdlvideo.put_pixel_color ~x:i ~y:0 surf Sdlvideo.white done; surf;; let whitev = let surf = Sdlvideo.create_RGB_surface_format screen [`SWSURFACE] ~w:1 ~h in for i = 0 to h-1 do Sdlvideo.put_pixel_color ~x:0 ~y:i surf Sdlvideo.white done; surf;; (* blit a rectangle border *) type action = Draw | Save | Restore | Update;; let border action x y w h = let hrect1 = {r_x=x;r_y=y;r_w=w;r_h=1} and vrect1 = {r_x=x;r_y=y;r_w=1;r_h=h} and hrect2 = {r_x=x;r_y=y+h;r_w=w;r_h=1} and vrect2 = {r_x=x+w;r_y=y;r_w=1;r_h=h} in match action with Draw -> blit_surface ~src:whiteh ~src_rect:{hrect1 with r_y=0;r_h=1} ~dst:screen ~dst_rect:hrect1 (); blit_surface ~src:whiteh ~src_rect:{hrect2 with r_y=0;r_h=1} ~dst:screen ~dst_rect:hrect2 (); blit_surface ~src:whitev ~src_rect:{vrect1 with r_x=0;r_w=1} ~dst:screen ~dst_rect:vrect1 (); blit_surface ~src:whitev ~src_rect:{vrect2 with r_x=0;r_w=1} ~dst:screen ~dst_rect:vrect2 () | Save -> blit_surface ~dst:shadowh ~dst_rect:{hrect1 with r_y=0;r_h=1} ~src:screen ~src_rect:hrect1 (); blit_surface ~dst:shadowh ~dst_rect:{hrect2 with r_y=1;r_h=1} ~src:screen ~src_rect:hrect2 (); blit_surface ~dst:shadowv ~dst_rect:{vrect1 with r_x=0;r_w=1} ~src:screen ~src_rect:vrect1 (); blit_surface ~dst:shadowv ~dst_rect:{vrect2 with r_x=1;r_w=1} ~src:screen ~src_rect:vrect2 () | Restore -> blit_surface ~src:shadowh ~src_rect:{hrect1 with r_y=0;r_h=1} ~dst:screen ~dst_rect:hrect1 (); blit_surface ~src:shadowh ~src_rect:{hrect2 with r_y=1;r_h=1} ~dst:screen ~dst_rect:hrect2 (); blit_surface ~src:shadowv ~src_rect:{vrect1 with r_x=0;r_w=1} ~dst:screen ~dst_rect:vrect1 (); blit_surface ~src:shadowv ~src_rect:{vrect2 with r_x=1;r_w=1} ~dst:screen ~dst_rect:vrect2 () | Update -> List.iter (fun r -> Sdlvideo.update_rect ~rect:r screen) [hrect1;hrect2;vrect1;vrect2] ;; (* draw *) let redraw () = Printf.eprintf "Computing...%!"; draw screen (compute()); Sdlvideo.update_rect screen; Printf.eprintf "done.\n%!";; (* event loop for zooming into the picture *) let rezoom x y w = let deltas = ((float !n)/.(float w)) in ofx := (!ofx +. (float x)) *. deltas; ofy := (!ofy +. (float y)) *. deltas; scale := !scale *. deltas; redraw();; let reset () = scale:=1.; ofx:=0.; ofy:=0.;redraw();; let refine () = res:=!res*2; redraw ();; let unrefine () = res:=!res/2; redraw ();; let zoom_in () = rezoom (!n/4) (!n/4) (!n/2);; let zoom_out () = rezoom (-(!n/2)) (-(!n/2)) (!n*2);; let dump () = Printf.eprintf "Dumping image taken at ofx: %f ofy: %f scale: %f\n%!" !ofx !ofy !scale; Sdlvideo.save_BMP screen (Printf.sprintf "mandels-ofx-%f-ofy-%f-scale-%f.bmp" !ofx !ofy !scale);; (* encode state machine here *) let rec init () = match wait_event () with | KEYDOWN {keysym=k} -> (match k with KEY_PLUS -> let _ = zoom_in() in init () | KEY_MINUS -> let _ = zoom_out() in init () | KEY_r -> let _ = refine () in init () | KEY_u -> let _ = unrefine () in init () | KEY_c -> let _ = reset() in init () | KEY_d -> let _ = dump() in init () | KEY_q -> Sdl.quit | _ -> init () ) | MOUSEBUTTONDOWN {mbe_x=x;mbe_y=y} -> track_rect x y (x,y,0,0) | _ -> init () and track_rect x y (ox,oy,ow,oh) = match wait_event () with | MOUSEBUTTONUP {mbe_x=x';mbe_y=y'} -> let bx,by,w,h = (min x x'), (min y y'), (abs (x'-x)), (abs (y'-y)) in (rezoom bx by (min w h); init()) | MOUSEMOTION {mme_x=x';mme_y=y'} -> let bx,by,w,h = (min x x'), (min y y'), (abs (x'-x)), (abs (y'-y)) in (* restore old image if necessary *) if ow>0 & oh>0 then begin border Restore ox oy ow oh; border Update ox oy ow oh end; (* save image if necessary *) if w>0 & h>0 then begin border Save bx by w h; (* draw the border *) border Draw bx by w h; border Update bx by w h; end; track_rect x y (bx,by,w,h) | _ -> track_rect x y (ox,oy,ow,oh) ;; let _ = let getarg i = max 1 (int_of_string Sys.argv.(i)) in try ncores := getarg 1;Printf.eprintf "Setting nproc = %d \n%!" !ncores; chunksize := getarg 2;Printf.eprintf "Setting chunksize = %d \n%!" !chunksize with _ -> () ;; redraw();; init() parmap-1.1.1/example/topnat.ml000066400000000000000000000005651361257663500163100ustar00rootroot00000000000000(* simple example to show how to use Parmap on the native toplevel *) (* just run ocamlnat and then #use this file *) #load "unix.cmxs";; #load "bigarray.cmxs";; #load "parmap.cmxs";; let mkn n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n;; Printf.printf "%d\n" (List.length (Parmap.parmap (fun x -> x+1) (Parmap.L (mkn 10000)) ~ncores:2));; parmap-1.1.1/parmap.opam000066400000000000000000000023001361257663500151410ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" build: [ ["dune" "subst"] {pinned} ["dune" "build" "-p" name "-j" jobs] ["dune" "runtest" "-p" name "-j" jobs] {with-test} ["dune" "build" "-p" name "@doc"] {with-doc} ] maintainer: ["Roberto Di Cosmo "] authors: ["Roberto Di Cosmo "] bug-reports: "https://github.com/rdicosmo/parmap/issues" homepage: "https://github.com/rdicosmo/parmap" license: "LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception" dev-repo: "git+https://github.com/rdicosmo/parmap.git" synopsis: "Minimalistic library allowing to exploit multicore architecture" description: """ Parmap is a minimalistic library allowing to exploit multicore architecture for OCaml programs with minimal modifications: if you want to use your many cores to accelerate an operation which happens to be a map, fold or map/fold (map-reduce), just use Parmap’s parmap, parfold and parmapfold primitives in place of the standard List.map and friends, and specify the number of subprocesses to use by the optional parameter ~ncores.""" depends: [ "dune" "dune-configurator" "base-bigarray" "base-unix" "ocaml" {>= "4.02.3"} ] parmap-1.1.1/src/000077500000000000000000000000001361257663500135775ustar00rootroot00000000000000parmap-1.1.1/src/bytearray.ml000066400000000000000000000076011361257663500161370ustar00rootroot00000000000000(***************************************************************************) (* bytearray.ml : functions for efficient marshaling to and from bigarrays *) (* *) (* Copyright 1999-2011, Jérôme Vouillon *) (* *) (* This library is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. A special linking *) (* exception to the GNU Lesser General Public License applies to this *) (* library, see the LICENSE file for more information. *) (***************************************************************************) open Bigarray type t = (char, int8_unsigned_elt, c_layout) Array1.t type tf = (float, float64_elt, c_layout) Array1.t let length = Bigarray.Array1.dim let create l = Bigarray.Array1.create Bigarray.char Bigarray.c_layout l let createf l = Bigarray.Array1.create Bigarray.float64 Bigarray.c_layout l (* let unsafe_blit_from_string s i a j l = for k = 0 to l - 1 do a.{j + k} <- s.[i + k] done let unsafe_blit_to_string a i s j l = for k = 0 to l - 1 do s.[j + k] <- a.{i + k} done *) external unsafe_blit_from_string : string -> int -> t -> int -> int -> unit = "ml_blit_string_to_bigarray" [@@noalloc] (* external unsafe_blit_to_bytes : t -> int -> bytes -> int -> int -> unit = "ml_blit_bigarray_to_string" "noalloc" *) (* let unsafe_sub a ofs len = let s = Bytes.create len in unsafe_blit_to_bytes a ofs s 0 len; Bytes.to_string s *) (* let to_string a = let l = length a in if l > Sys.max_string_length then invalid_arg "Bytearray.to_string" else unsafe_sub a 0 l *) let of_string s = let l = String.length s in let a = create l in unsafe_blit_from_string s 0 a 0 l; a let mmap_of_string fd s = let l = String.length s in let ba = Bigarray.array1_of_genarray @@ Parmap_compat.map_file fd Bigarray.char Bigarray.c_layout true [|l|] in unsafe_blit_from_string s 0 ba 0 l; ba (* let sub a ofs len = if ofs < 0 || len < 0 || ofs > length a - len || len > Sys.max_string_length then invalid_arg "Bytearray.sub" else unsafe_sub a ofs len *) let rec prefix_rec a i a' i' l = l = 0 || (a.{i} = a'.{i'} && prefix_rec a (i + 1) a' (i' + 1) (l - 1)) let prefix a a' i = let l = length a in let l' = length a' in i <= l' - l && prefix_rec a 0 a' i l let blit_from_string s i a j l = if l < 0 || i < 0 || i > String.length s - l || j < 0 || j > length a - l then invalid_arg "Bytearray.blit_from_string" else unsafe_blit_from_string s i a j l (* let blit_to_bytes a i s j l = if l < 0 || i < 0 || i > length a - l || j < 0 || j > Bytes.length s - l then invalid_arg "Bytearray.blit_to_bytes" else unsafe_blit_to_bytes a i s j l *) external marshal : 'a -> Marshal.extern_flags list -> t = "ml_marshal_to_bigarray" external marshal_to_buffer : t -> int -> 'a -> Marshal.extern_flags list -> int = "ml_marshal_to_bigarray_buffer" external unmarshal : t -> int -> 'a = "ml_unmarshal_from_bigarray" external unsafe_blit_from_floatarray : float array -> int -> tf -> int -> int -> unit = "ml_blit_floatarray_to_bigarray" [@@noalloc] external unsafe_blit_to_floatarray : tf -> int -> float array -> int -> int -> unit = "ml_blit_bigarray_to_floatarray" [@@noalloc] let to_floatarray a l = let fa = Obj.obj (Obj.new_block Obj.double_array_tag l) in unsafe_blit_to_floatarray a 0 fa 0 l; fa let to_this_floatarray fa a l = unsafe_blit_to_floatarray a 0 fa 0 l; fa let of_floatarray fa = let l = Array.length fa in let a = createf l in unsafe_blit_from_floatarray fa 0 a 0 l; a parmap-1.1.1/src/bytearray.mli000066400000000000000000000031341361257663500163050ustar00rootroot00000000000000(***************************************************************************) (* Copyright 1999-2010, Jérôme Vouillon *) (* *) (* This library is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. A special linking *) (* exception to the GNU Lesser General Public License applies to this *) (* library, see the LICENSE file for more information. *) (***************************************************************************) type t = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t type tf = (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t val create : int -> t val length : t -> int (* val to_string : t -> string *) val of_string : string -> t val mmap_of_string : Unix.file_descr -> string -> t val to_floatarray : tf -> int -> float array val to_this_floatarray : float array -> tf -> int -> float array val of_floatarray : float array -> tf (* val sub : t -> int -> int -> string *) val blit_from_string : string -> int -> t -> int -> int -> unit (* val blit_to_bytes : t -> int -> bytes -> int -> int -> unit *) val prefix : t -> t -> int -> bool val marshal : 'a -> Marshal.extern_flags list -> t val unmarshal : t -> int -> 'a val marshal_to_buffer : t -> int -> 'a -> Marshal.extern_flags list -> int parmap-1.1.1/src/bytearray_stubs.c000066400000000000000000000041341361257663500171670ustar00rootroot00000000000000/* bytearray_stubs.c : C routines for bytearray.ml */ /* Copyright Jérôme Vouillon 1999-2010 (see LICENCE for distribution conditions) */ #include #include "caml/intext.h" #include "caml/bigarray.h" #define Array_data(a, i) (((char *) a->data) + Long_val(i)) #define Floatarray_data(a, i) (((char *) a->data) + 8 * Long_val(i)) CAMLprim value ml_marshal_to_bigarray(value v, value flags) { char *buf; long len; output_value_to_malloc(v, flags, &buf, &len); return alloc_bigarray(BIGARRAY_UINT8 | BIGARRAY_C_LAYOUT | BIGARRAY_MANAGED, 1, buf, &len); } CAMLprim value ml_marshal_to_bigarray_buffer(value b, value ofs, value v, value flags) { struct caml_bigarray *b_arr = Bigarray_val(b); return Val_long(caml_output_value_to_block(v, flags, Array_data (b_arr, ofs), b_arr->dim[0] - Long_val(ofs))); } CAMLprim value ml_unmarshal_from_bigarray(value b, value ofs) { struct caml_bigarray *b_arr = Bigarray_val(b); return input_value_from_block (Array_data (b_arr, ofs), b_arr->dim[0] - Long_val(ofs)); } CAMLprim value ml_blit_string_to_bigarray (value s, value i, value a, value j, value l) { char *src = String_val(s) + Int_val(i); char *dest = Array_data(Bigarray_val(a), j); memcpy(dest, src, Long_val(l)); return Val_unit; } CAMLprim value ml_blit_bigarray_to_string (value a, value i, value s, value j, value l) { char *src = Array_data(Bigarray_val(a), i); char *dest = String_val(s) + Long_val(j); memcpy(dest, src, Long_val(l)); return Val_unit; } CAMLprim value ml_blit_floatarray_to_bigarray (value fa, value i, value a, value j, value l) { int w = 8; char *src = Bp_val(fa) + Long_val(i)*w; char *dest = Floatarray_data(Bigarray_val(a), j); memcpy(dest, src, Long_val(l)*w); return Val_unit; } CAMLprim value ml_blit_bigarray_to_floatarray (value a, value i, value fa, value j, value l) { int w = 8; char *src = Floatarray_data(Bigarray_val(a), i); char *dest = Bp_val(fa) + Long_val(j)*w; memcpy(dest, src, Long_val(l)*w); return Val_unit; } parmap-1.1.1/src/dune000066400000000000000000000005411361257663500144550ustar00rootroot00000000000000(library (public_name parmap) (synopsis "Parallel map primitive for multicores") (wrapped false) (libraries bigarray unix) (c_names bytearray_stubs setcore_stubs)) (documentation (package parmap) (mld_files index) ) (rule (targets parmap_compat.ml setcore_stubs.h) (deps (:discover ../config/discover.exe)) (action (run %{discover}))) parmap-1.1.1/src/index.mld000066400000000000000000000000411361257663500153770ustar00rootroot00000000000000{1 The Parmap Library} {!Parmap}parmap-1.1.1/src/parmap.ml000066400000000000000000000603301361257663500154130ustar00rootroot00000000000000(**************************************************************************) (* ParMap: a simple library to perform Map computations on a multi-core *) (* *) (* Author(s): Marco Danelutto, Roberto Di Cosmo *) (* *) (* This library is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. A special linking *) (* exception to the GNU Lesser General Public License applies to this *) (* library, see the LICENSE file for more information. *) (**************************************************************************) module Utils = Parmap_utils (* OS related constants *) (* sequence type, subsuming lists and arrays *) type 'a sequence = L of 'a list | A of 'a array let debug_enabled = ref false (* toggle debugging *) let debugging b = debug_enabled:=b (* default number of cores, and a setter function *) let default_ncores=ref (max 2 (Setcore.numcores()-1));; let set_default_ncores n = default_ncores := n;; let get_default_ncores () = !default_ncores;; let ncores = ref 0;; let set_ncores n = ncores := n;; let get_ncores () = !ncores (* core mapping *) let no_core_pinning = ref false let disable_core_pinning () = no_core_pinning := true let enable_core_pinning () = no_core_pinning := false let core_mapping = ref None let set_core_mapping (m: int array) = core_mapping := Some m (* worker process rank *) let masters_rank = -1 let rank = ref masters_rank let set_rank n = rank := n let get_rank () = !rank (* exception handling code *) let handle_exc core msg = Utils.log_error "aborting due to exception on core %d: %s" core msg; exit 1;; (* Helper functions for stdout/stderr redirection *) let can_redirect path = if not(Sys.file_exists path) then try Unix.mkdir path 0o777; true with Unix.Unix_error(e,_s,_s') -> (* another job may have created it between the check and the mkdir *) if e == Unix.EEXIST then true else begin (Printf.eprintf "[Pid %d]: Error creating %s : %s; proceeding \ without stdout/stderr redirection\n%!" (Unix.getpid ()) path (Unix.error_message e)); false end else true let log_debug fmt = Printf.kprintf ( if !debug_enabled then begin (fun s -> Format.eprintf "[Parmap]: %s@." s) end else ignore ) fmt (* freopen emulation, from Xavier's suggestion on OCaml mailing list *) let reopen_out outchan path fname = if can_redirect path then begin flush outchan; let filename = Filename.concat path fname in let fd1 = Unix.descr_of_out_channel outchan in let fd2 = Unix.openfile filename [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_TRUNC] 0o666 in Unix.dup2 fd2 fd1; Unix.close fd2 end else () (* send stdout and stderr to a file to avoid mixing output from different cores, if enabled *) let redirect ?(path = (Printf.sprintf "/tmp/.parmap.%d" (Unix.getpid ()))) ~id = reopen_out stdout path (Printf.sprintf "stdout.%d" id); reopen_out stderr path (Printf.sprintf "stderr.%d" id);; (* unmarshal from a mmap seen as a bigarray *) let unmarshal fd = let a = Bigarray.array1_of_genarray @@ Parmap_compat.map_file fd Bigarray.char Bigarray.c_layout true [|-1|] in let res = Bytearray.unmarshal a 0 in Unix.close fd; res (* marshal to a mmap seen as a bigarray *) (* System dependent notes: (* a reasonable size for mmapping a file containing even huge result data *) let huge_size = if Sys.word_size = 64 then 1 lsl 32 else 1 lsl 26 - on Linux kernels, we might allocate a mmapped memory area of huge_size and marshal into it directly let ba = Bigarray.array1_of_genarray @@ Parmap_compat.map_file fd Bigarray.char Bigarray.c_layout true huge_size in ignore(Bytearray.marshal_to_buffer ba 0 v [Marshal.Closures]); Unix.close fd - to be compatible with other systems, notably Mac OS X, which insist in allocating *all* the declared memory area even for a sparse file, we must choose a less efficient approach: * marshal the value v to a string s, and compute its size * allocate a mmap of that exact size, * copy the string to that mmap this allocates twice as much memory, and incurs an extra copy of the value v *) let marshal fd v = let s = Marshal.to_string v [Marshal.Closures] in ignore(Bytearray.mmap_of_string fd s) (* Exit the program with calling [at_exit] handlers *) external sys_exit : int -> 'a = "caml_sys_exit" let spawn_many n ~in_subprocess = let rec loop i acc = if i = n then acc else match Unix.fork() with 0 -> (* [at_exit] handlers are called in reverse order of registration. By registering a handler that exits prematurely, we prevent the execution of handlers registered before the fork. This ignores the exit code provided by the user, but we ignore it anyway in [wait_for_pids]. *) at_exit (fun () -> sys_exit 0); set_rank i; in_subprocess i; exit 0 | -1 -> Utils.log_error "fork error: pid %d; i=%d" (Unix.getpid()) i; loop (i + 1) acc | pid -> loop (i + 1) (pid :: acc) in (* call the GC before forking *) Gc.compact (); loop 0 [] let wait_for_pids pids = let rec wait_for_pid pid = try ignore(Unix.waitpid [] pid : int * Unix.process_status) with | Unix.Unix_error (Unix.ECHILD, _, _) -> () | Unix.Unix_error (Unix.EINTR, _, _) -> wait_for_pid pid in List.iter wait_for_pid pids let run_many n ~in_subprocess = wait_for_pids (spawn_many n ~in_subprocess) (* a simple mapper function that computes 1/nth of the data on each of the n cores in one iteration *) let simplemapper (init:int -> unit) (finalize: unit -> unit) ncores' compute opid al collect = (* flush everything *) flush_all(); (* init task parameters *) let ln = Array.length al in set_ncores (min ln (max 1 ncores')); let chunksize = max 1 (ln / !ncores) in log_debug "simplemapper on %d elements, on %d cores, chunksize = %d%!" ln !ncores chunksize; (* create descriptors to mmap *) let fdarr=Array.init !ncores (fun _ -> Utils.tempfd()) in (* run children *) run_many !ncores ~in_subprocess:(fun i -> init i; (* call initialization function *) at_exit finalize; (* register finalization function *) let lo=i*chunksize in let hi=if i = !ncores - 1 then ln - 1 else (i + 1) * chunksize - 1 in let exc_handler e j = (* handle an exception at index j *) Utils.log_error "error at index j=%d in (%d,%d), chunksize=%d of a total of \ %d got exception %s on core %d \n%!" j lo hi chunksize (hi-lo+1) (Printexc.to_string e) i; exit 1 in let v = compute al lo hi opid exc_handler in marshal fdarr.(i) v); (* read in all data *) let res = ref [] in (* iterate in reverse order, to accumulate in the right order *) for i = 0 to !ncores - 1 do res:= ((unmarshal fdarr.((!ncores-1)-i)):'d)::!res; done; (* collect all results *) collect !res (* a simple iteration function that iterates on 1/nth of the data on each of the n cores *) let simpleiter init finalize ncores' compute al = (* flush everything *) flush_all(); (* init task parameters *) let ln = Array.length al in set_ncores (min ln (max 1 ncores')); let chunksize = max 1 (ln / !ncores) in log_debug "simplemapper on %d elements, on %d cores, chunksize = %d%!" ln !ncores chunksize; (* run children *) run_many !ncores ~in_subprocess:(fun i -> init i; (* call initialization function *) at_exit finalize; (* register finalization function *) let lo=i*chunksize in let hi=if i= !ncores - 1 then ln-1 else (i+1)*chunksize-1 in let exc_handler e j = (* handle an exception at index j *) Utils.log_error "error at index j=%d in (%d,%d), chunksize=%d of a total of \ %d got exception %s on core %d \n%!" j lo hi chunksize (hi-lo+1) (Printexc.to_string e) i; exit 1 in compute al lo hi exc_handler); (* return with no value *) (* a more sophisticated mapper function, with automatic load balancing *) (* the type of messages exchanged between master and workers *) type msg_to_master = Ready of int | Error of int * string type msg_to_worker = Finished | Task of int let setup_children_chans oc pipedown ?fdarr i = (if !no_core_pinning then () else match !core_mapping with (* map process i to core i, or, if a core_mapping exist, to core_mapping.(i), reusing core_mapping as many times as needed *) | None -> Setcore.setcore i | Some m -> let ml = Array.length m in Setcore.setcore m.(i mod ml)); (* close the other ends of the pipe and convert my ends to ic/oc *) Unix.close (snd pipedown.(i)); let pid = Unix.getpid() in let ic = Unix.in_channel_of_descr (fst pipedown.(i)) in let receive () = Marshal.from_channel ic in let signal v = Marshal.to_channel oc v []; flush oc in let return v = let d = Unix.gettimeofday() in let _ = match fdarr with Some fdarr -> marshal fdarr.(i) v | None -> () in log_debug "worker elapsed %f in marshalling" (Unix.gettimeofday() -. d) in let finish () = (log_debug "shutting down (pid=%d)\n%!" pid; try close_in ic; close_out oc with _ -> () ); exit 0 in receive, signal, return, finish, pid (* parametric mapper primitive that captures the parallel structure *) let mapper (init:int -> unit) (finalize:unit -> unit) ncores' ~chunksize compute opid al collect = let ln = Array.length al in if ln=0 then (collect []) else begin set_ncores (min ln (max 1 ncores')); log_debug "mapper on %d elements, on %d cores%!" ln !ncores; match chunksize with None -> (* no need of load balancing *) simplemapper init finalize !ncores compute opid al collect | Some v when !ncores >= ln/v -> (* no need of load balancing if more cores than tasks *) simplemapper init finalize !ncores compute opid al collect | Some v -> (* init task parameters : ntasks > 0 here, as otherwise ncores >= 1 >= ln/v = ntasks and we would take the branch above *) let chunksize = v and ntasks = ln/v in (* flush everything *) flush_all (); (* create descriptors to mmap *) let fdarr=Array.init !ncores (fun _ -> Utils.tempfd()) in (* setup communication channel with the workers *) let pipedown=Array.init !ncores (fun _ -> Unix.pipe ()) in let pipeup_rd,pipeup_wr=Unix.pipe () in let oc_up = Unix.out_channel_of_descr pipeup_wr in (* run children *) let pids = spawn_many !ncores ~in_subprocess:(fun i -> init i; (* call initialization function *) at_exit finalize; (* register finalization function *) let d=Unix.gettimeofday() in (* primitives for communication *) Unix.close pipeup_rd; let receive,signal,return,finish,pid = setup_children_chans oc_up pipedown ~fdarr i in let reschunk=ref opid in let computetask n = (* compute chunk number n *) let lo=n*chunksize in let hi=if n=ntasks-1 then ln-1 else (n+1)*chunksize-1 in let exc_handler e j = (* handle an exception at index j *) begin let errmsg = Printexc.to_string e in Utils.log_error "error at index j=%d in (%d,%d), chunksize=%d of a \ total of %d got exception %s on core %d \n%!" j lo hi chunksize (hi-lo+1) errmsg i; signal (Error (i,errmsg): msg_to_master); finish() end in reschunk:= compute al lo hi !reschunk exc_handler; log_debug "worker on core %d (pid=%d), segment (%d,%d) of data of \ length %d, chunksize=%d finished in %f seconds" i pid lo hi ln chunksize (Unix.gettimeofday() -. d) in while true do (* ask for work until we are finished *) signal (Ready i); match receive() with | Finished -> return (!reschunk:'d); finish () | Task n -> computetask n done) in (* close unused ends of the pipes *) Array.iter (fun (rfd,_) -> Unix.close rfd) pipedown; Unix.close pipeup_wr; (* get ic/oc/wfdl *) let ocs= Array.init !ncores (fun n -> Unix.out_channel_of_descr (snd pipedown.(n))) in let ic=Unix.in_channel_of_descr pipeup_rd in (* feed workers until all tasks are finished *) for i=0 to ntasks-1 do match Marshal.from_channel ic with Ready w -> (log_debug "sending task %d to worker %d" i w; let oc = ocs.(w) in (Marshal.to_channel oc (Task i) []); flush oc) | (Error (core,msg): msg_to_master) -> handle_exc core msg done; (* send termination token to all children *) Array.iter (fun oc -> Marshal.to_channel oc Finished []; flush oc; close_out oc ) ocs; (* wait for all children to terminate *) wait_for_pids pids; (* read in all data *) let res = ref [] in (* iterate in reverse order, to accumulate in the right order *) for i = 0 to !ncores-1 do res:= ((unmarshal fdarr.((!ncores-1)-i)):'d)::!res; done; (* collect all results *) collect !res end (* parametric iteration primitive that captures the parallel structure *) let geniter init finalize ncores' ~chunksize compute al = let ln = Array.length al in if ln=0 then () else begin set_ncores (min ln (max 1 ncores')); log_debug "geniter on %d elements, on %d cores%!" ln !ncores; match chunksize with None -> simpleiter init finalize !ncores compute al (* no need of load balancing *) | Some v when !ncores >= ln/v -> simpleiter init finalize !ncores compute al (* no need of load balancing *) | Some v -> (* init task parameters *) let chunksize = v and ntasks = ln/v in (* flush everything *) flush_all (); (* setup communication channel with the workers *) let pipedown=Array.init !ncores (fun _ -> Unix.pipe ()) in let pipeup_rd,pipeup_wr=Unix.pipe () in let oc_up = Unix.out_channel_of_descr pipeup_wr in (* spawn children *) let pids = spawn_many !ncores ~in_subprocess:(fun i -> init i; (* call initialization function *) at_exit finalize; (* register finalization function *) let d=Unix.gettimeofday() in (* primitives for communication *) Unix.close pipeup_rd; let receive,signal,return,finish,pid = setup_children_chans oc_up pipedown i in let computetask n = (* compute chunk number n *) let lo=n*chunksize in let hi=if n=ntasks-1 then ln-1 else (n+1)*chunksize-1 in let exc_handler e j = (* handle an exception at index j *) begin let errmsg = Printexc.to_string e in Utils.log_error "error at index j=%d in (%d,%d), chunksize=%d of \ a total of %d got exception %s on core %d \n%!" j lo hi chunksize (hi-lo+1) errmsg i; signal (Error (i,errmsg): msg_to_master); finish() end in compute al lo hi exc_handler; log_debug "worker on core %d (pid=%d), segment (%d,%d) of data \ of length %d, chunksize=%d finished in %f seconds" i pid lo hi ln chunksize (Unix.gettimeofday() -. d) in while true do (* ask for work until we are finished *) signal (Ready i); match receive() with | Finished -> return(); finish () | Task n -> computetask n done) in (* close unused ends of the pipes *) Array.iter (fun (rfd,_) -> Unix.close rfd) pipedown; Unix.close pipeup_wr; (* get ic/oc/wfdl *) let ocs=Array.init !ncores (fun n -> Unix.out_channel_of_descr (snd pipedown.(n))) in let ic=Unix.in_channel_of_descr pipeup_rd in (* feed workers until all tasks are finished *) for i=0 to ntasks-1 do match Marshal.from_channel ic with Ready w -> (log_debug "sending task %d to worker %d" i w; let oc = ocs.(w) in (Marshal.to_channel oc (Task i) []); flush oc) | (Error (core,msg): msg_to_master) -> handle_exc core msg done; (* send termination token to all children *) Array.iter (fun oc -> Marshal.to_channel oc Finished []; flush oc; close_out oc ) ocs; (* wait for all children to terminate *) wait_for_pids pids; (* no data to return *) end (* the parallel mapfold function *) let parmapifold ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?(chunksize) (f:int -> 'a -> 'b) (s:'a sequence) (op:'b->'c->'c) (opid:'c) (concat:'c->'c->'c) : 'c= (* enforce array to speed up access to the list elements *) let al = match s with A al -> al | L l -> Array.of_list l in let compute al lo hi previous exc_handler = (* iterate in reverse order, to accumulate in the right order *) let r = ref previous in for j=0 to (hi-lo) do try let idx = hi-j in r := op (f idx (Array.unsafe_get al idx)) !r; with e -> exc_handler e j done; !r in mapper init finalize ncores ~chunksize compute opid al (fun r -> Utils.fold_right concat r opid) let parmapfold ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?ncores ?(chunksize) (f:'a -> 'b) (s:'a sequence) (op:'b->'c->'c) (opid:'c) (concat:'c->'c->'c) : 'c= parmapifold ~init ~finalize ?ncores ?chunksize (fun _ x -> f x) s op opid concat (* the parallel map function *) let parmapi ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?chunksize (f:int ->'a -> 'b) (s:'a sequence) : 'b list= (* enforce array to speed up access to the list elements *) let al = match s with A al -> al | L l -> Array.of_list l in let compute al lo hi previous exc_handler = (* iterate in reverse order, to accumulate in the right order, and add to acc *) let f' j = try let idx = lo+j in f idx (Array.unsafe_get al idx) with e -> exc_handler e j in let rec aux acc = function 0 -> (f' 0)::acc | n -> aux ((f' n)::acc) (n-1) in aux previous (hi-lo) in mapper init finalize ncores ~chunksize compute [] al (fun r -> Utils.concat_tr r) let parmap ?init ?finalize ?ncores ?chunksize (f:'a -> 'b) (s:'a sequence) : 'b list= parmapi ?init ?finalize ?ncores ?chunksize (fun _ x -> f x) s (* the parallel fold function *) let parfold ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?chunksize (op:'a -> 'b -> 'b) (s:'a sequence) (opid:'b) (concat:'b->'b->'b) : 'b= parmapfold ~init ~finalize ~ncores ?chunksize (fun x -> x) s op opid concat (* the parallel map function, on arrays *) let mapi_range lo hi (f:int -> 'a -> 'b) a = let l = hi-lo in if l < 0 then [||] else begin let r = Array.make (l+1) (f lo (Array.unsafe_get a lo)) in for i = 1 to l do let idx = lo+i in Array.unsafe_set r i (f idx (Array.unsafe_get a idx)) done; r end let array_parmapi ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?chunksize (f:int -> 'a -> 'b) (al:'a array) : 'b array= let compute a lo hi previous exc_handler = try Array.concat [(mapi_range lo hi f a);previous] with e -> exc_handler e lo in mapper init finalize ncores ~chunksize compute [||] al (fun r -> Array.concat r) let array_parmap ?init ?finalize ?ncores ?chunksize (f:'a -> 'b) (al:'a array) : 'b array= array_parmapi ?init ?finalize ?ncores ?chunksize (fun _ x -> f x) al (* This code is highly optimised for operations on float arrays: - knowing in advance the size of the result allows to pre-allocate it in a shared memory space as a Bigarray; - to write in the Bigarray memory area using the unsafe functions for Arrays, we trick the OCaml compiler into using the Bigarray memory as an Array as follows Array.unsafe_get (Obj.magic arr_out) 1 This works because OCaml compiles access to float arrays as unboxed data, without further integrity checks; - the final copy into a real OCaml array is done via a memcpy in C. This approach gives a performance which is 2 to 3 times higher w.r.t. array_parmap, at the price of using Obj.magic and knowledge on the internal representation of arrays and bigarrays. *) exception WrongArraySize type buf= (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t * int;; (* should be a long int some day *) let init_shared_buffer a = let size = Array.length a in let fd = Utils.tempfd() in let arr = Bigarray.array1_of_genarray @@ Parmap_compat.map_file fd Bigarray.float64 Bigarray.c_layout true [|size|] in (* The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. http://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html *) Unix.close fd; (arr,size) let array_float_parmapi ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?chunksize ?result ?sharedbuffer (f:int -> 'a -> float) (al:'a array) : float array = let size = Array.length al in if size=0 then [| |] else begin let barr_out = match sharedbuffer with Some (arr,s) -> if s fst (init_shared_buffer al) in (* trick the compiler into accessing the Bigarray memory area as a float array: the data in Bigarray is placed at offset 1 w.r.t. a normal array, so we get a pointer to that zone into arr_out_as_array, and have it typed as a float array *) let barr_out_as_array = Array.unsafe_get (Obj.magic barr_out) 1 in let compute _ lo hi _ exc_handler = try for i=lo to hi do Array.unsafe_set barr_out_as_array i (f i (Array.unsafe_get al i)) done with e -> exc_handler e lo in mapper init finalize ncores ~chunksize compute () al (fun _r -> ()); let res = match result with None -> Bytearray.to_floatarray barr_out size | Some a -> if Array.length a < size then (Utils.log_error "result array is too small to hold the result in \ array_float_parmap"; raise WrongArraySize) else Bytearray.to_this_floatarray a barr_out size in res end let array_float_parmap ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?ncores ?chunksize ?result ?sharedbuffer (f:'a -> float) (al:'a array) : float array = array_float_parmapi ~init ~finalize ?ncores ?chunksize ?result ?sharedbuffer (fun _ x -> f x) al (* the parallel iteration function *) let pariteri ?(init = fun _ -> ()) ?(finalize = fun () -> ()) ?(ncores= !default_ncores) ?chunksize (f:int -> 'a -> unit) (s:'a sequence) : unit= (* enforce array to speed up access to the list elements *) let al = match s with A al -> al | L l -> Array.of_list l in let compute al lo hi exc_handler = (* iterate on the given segment *) let f' j = try let idx = lo+j in f idx (Array.unsafe_get al idx) with e -> exc_handler e j in for i = 0 to hi-lo do f' i done in geniter init finalize ncores ~chunksize compute al let pariter ?init ?finalize ?ncores ?chunksize (f:'a -> unit) (s:'a sequence) : unit= pariteri ?init ?finalize ?ncores ?chunksize (fun _ x -> f x) s parmap-1.1.1/src/parmap.mli000066400000000000000000000264651361257663500155770ustar00rootroot00000000000000(**************************************************************************) (* ParMap: a simple library to perform Map computations on a multi-core *) (* *) (* Author(s): Marco Danelutto, Roberto Di Cosmo *) (* *) (* This library is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. A special linking *) (* exception to the GNU Lesser General Public License applies to this *) (* library, see the LICENSE file for more information. *) (**************************************************************************) (** Module [Parmap]: efficient parallel map, fold and mapfold on lists and arrays on multicores. All the primitives allow to control the granularity of the parallelism via an optional parameter [chunksize]: if [chunksize] is omitted, the input sequence is split evenly among the available cores; if [chunksize] is specified, the input data is split in chunks of size [chunksize] and dispatched to the available cores using an on demand strategy that ensures automatic load balancing. A specific primitive {!array_float_parmap} is provided for fast operations on float arrays. *) (** {1 Configuring available cores} *) (** {2 Setting and getting the default value for ncores } *) val set_default_ncores : int -> unit val get_default_ncores : unit -> int (** {2 Getting ncores being used during parallel execution } *) val get_ncores : unit -> int (** {2 Enabling/disabling processes core pinning } *) val disable_core_pinning: unit -> unit (** [disable_core_pinning ()] will prevent forked out processes from being pinned to a specific core. WARNING: this may have a negative impact on performance, but might be necessary on systems where several parmap computations are running concurrently. *) val enable_core_pinning: unit -> unit (** [enable_core_pinning ()] turns on core pinning (it is on by default). *) (** {2 Setting and getting an explicity mapping from processes to cores } *) val set_core_mapping: int array -> unit (** [set_core_mapping m] installs the array [m] as the mapping to be used to pin processes to cores. Process [i] will be pinned to core [m.(i mod Array.length m)]. *) (** Getting the current worker rank. The master process has rank -1. Other processes have the rank at which they were forked out (a worker's rank is in [0..ncores-1]) *) val get_rank : unit -> int (** {1 Parallel map and folds} *) type 'a sequence = L of 'a list | A of 'a array;; (** {2 Generic operations} *) (** The {!parmapfold}, {!parfold} and {!parmap} generic functions, for efficiency reasons, convert the input data into an array internally, so we provide the ['a sequence] type to allow passing an array directly as input. If you want to perform a parallel map operation on an array, use {!array_parmap} or {!array_float_parmap} instead. *) (** The optional [init] (resp. [finalize]) function is called once by each child process just after creation (resp. just before exit). [init] and [finalize] both default to doing nothing. [init i] takes the child rank [i] as parameter (first forked child has rank 0, next 1, etc.). *) (** {3 Parallel mapfold} *) val parmapfold : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ('a -> 'b) -> 'a sequence -> ('b-> 'c -> 'c) -> 'c -> ('c->'c->'c) -> 'c (** [parmapfold ~ncores:n f (L l) op b concat ] computes [List.fold_right op (List.map f l) b] by forking [n] processes on a multicore machine. You need to provide the extra [concat] operator to combine the partial results of the fold computed on each core. If 'b = 'c, then [concat] may be simply [op]. The order of computation in parallel changes w.r.t. sequential execution, so this function is only correct if [op] and [concat] are associative and commutative. If the optional [chunksize] parameter is specified, the processes compute the result in an on-demand fashion on blocks of size [chunksize]. [parmapfold ~ncores:n f (A a) op b concat ] computes [Array.fold_right op (Array.map f a) b] *) (** {3 Parallel fold} *) val parfold: ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ('a -> 'b -> 'b) -> 'a sequence -> 'b -> ('b->'b->'b) -> 'b (** [parfold ~ncores:n op (L l) b concat] computes [List.fold_right op l b] by forking [n] processes on a multicore machine. You need to provide the extra [concat] operator to combine the partial results of the fold computed on each core. If 'b = 'c, then [concat] may be simply [op]. The order of computation in parallel changes w.r.t. sequential execution, so this function is only correct if [op] and [concat] are associative and commutative. If the optional [chunksize] parameter is specified, the processes compute the result in an on-demand fashion on blocks of size [chunksize]. [parfold ~ncores:n op (A a) b concat] similarly computes [Array.fold_right op a b]. *) (** {3 Parallel map} *) val parmap : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ('a -> 'b) -> 'a sequence -> 'b list (** [parmap ~ncores:n f (L l) ] computes [List.map f l] by forking [n] processes on a multicore machine. [parmap ~ncores:n f (A a) ] computes [Array.map f a] by forking [n] processes on a multicore machine. If the optional [chunksize] parameter is specified, the processes compute the result in an on-demand fashion on blocks of size [chunksize]; this provides automatic load balancing for unbalanced computations, but the order of the result is no longer guaranteed to be preserved. *) (** {3 Parallel iteration} *) val pariter : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ('a -> unit) -> 'a sequence -> unit (** [pariter ~ncores:n f (L l) ] computes [List.iter f l] by forking [n] processes on a multicore machine. [parmap ~ncores:n f (A a) ] computes [Array.iter f a] by forking [n] processes on a multicore machine. If the optional [chunksize] parameter is specified, the processes perform the computation in an on-demand fashion on blocks of size [chunksize]; this provides automatic load balancing for unbalanced computations. *) (** {3 Parallel mapfold, indexed} *) val parmapifold : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> (int -> 'a -> 'b) -> 'a sequence -> ('b-> 'c -> 'c) -> 'c -> ('c->'c->'c) -> 'c (** Like parmapfold, but the map function gets as an extra argument the index of the mapped element *) (** {3 Parallel map, indexed} *) val parmapi : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> (int -> 'a -> 'b) -> 'a sequence -> 'b list (** Like parmap, but the map function gets as an extra argument the index of the mapped element *) (** {3 Parallel iteration, indexed} *) val pariteri : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> (int -> 'a -> unit) -> 'a sequence -> unit (** Like pariter, but the iterated function gets as an extra argument the index of the sequence element *) (** {3 Parallel map on arrays} *) val array_parmap : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ('a -> 'b) -> 'a array -> 'b array (** [array_parmap ~ncores:n f a ] computes [Array.map f a] by forking [n] processes on a multicore machine. If the optional [chunksize] parameter is specified, the processes compute the result in an on-demand fashion on blochs of size [chunksize]; this provides automatic load balancing for unbalanced computations, but the order of the result is no longer guaranteed to be preserved. *) (** {3 Parallel map on arrays, indexed} *) val array_parmapi : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> (int -> 'a -> 'b) -> 'a array -> 'b array (** Like array_parmap, but the map function gets as an extra argument the index of the mapped element *) (** {2 Float array operations} *) exception WrongArraySize type buf val init_shared_buffer : float array -> buf (** [init_shared_buffer a] creates a new memory mapped shared buffer big enough to hold a float array of the size of [a]. This buffer can be reused in a series of calls to [array_float_parmap], avoiding the cost of reallocating it each time. *) (** {3 Parallel map on float arrays } *) val array_float_parmap : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ?result: float array -> ?sharedbuffer: buf -> ('a -> float) -> 'a array -> float array (** [array_float_parmap ~ncores:n f a ] computes [Array.map f a] by forking [n] processes on a multicore machine, and preallocating the resulting array as shared memory, which allows significantly more efficient computation than calling the generic array_parmap function. If the optional [chunksize] parameter is specified, the processes compute the result in an on-demand fashion on blochs of size [chunksize]; this provides automatic load balancing for unbalanced computations, *and* the order of the result is still guaranteed to be preserved. In case you already have at hand an array where to store the result, you can squeeze out some more cpu cycles by passing it as optional parameter [result]: this will avoid the creation of a result array, which can be costly for very large data sets. Raises [WrongArraySize] if [result] is too small to hold the data. It is possible to share the same preallocated shared memory space across calls, by initialising the space calling [init_shared_buffer a] and passing the result as the optional [sharedbuffer] parameter to each subsequent call to [array_float_parmap]. Raises WrongArraySize if [sharedbuffer] is too small to hold the input data. *) (** {3 Parallel map on float arrays, indexed } *) val array_float_parmapi : ?init:(int -> unit) -> ?finalize:(unit -> unit) -> ?ncores:int -> ?chunksize:int -> ?result: float array -> ?sharedbuffer: buf -> (int -> 'a -> float) -> 'a array -> float array (** Like array_float_parmap, but the map function gets as an extra argument the index of the mapped element *) (** {1 Debugging and Helpers} *) val debugging : bool -> unit (** Enable or disable debugging code in the library; default: false *) val redirect : ?path:string -> id:int -> unit (** Helper function that redirects stdout and stderr to files located in the directory [path], carrying names of the shape stdout.NNN and stderr.NNN where NNN is the [id] of the used core. Useful when writing initialisation functions to be passed as [init] argument to the parallel combinators. The default value for [path] is /tmp/.parmap.PPPP with PPPP the process id of the main program. *) parmap-1.1.1/src/parmap_utils.ml000066400000000000000000000025351361257663500166360ustar00rootroot00000000000000 let log_error fmt = Printf.kprintf (fun s -> Format.eprintf "[Parmap]: %s@.%!" s) fmt (* tail recursive version of List.append *) let append_tr l1 l2 = let rec aux acc = function [] -> acc | a::r -> aux (a::acc) r in aux l2 (List.rev l1) (* tail recursive version of List.concat *) let concat_tr (l: 'a list) = List.fold_left (fun acc l -> append_tr l acc) [] (List.rev l) (* tail recursive version of List.fold_right from ExtLib *) let fold_right f l init = let fold_right_max = 1000 in let rec tail_loop acc = function | [] -> acc | h :: t -> tail_loop (f h acc) t in let rec loop n = function | [] -> init | h :: t -> if n < fold_right_max then f h (loop (n+1) t) else f h (tail_loop init (List.rev t)) in loop 0 l (* would be [? a | a <- startv--endv] using list comprehension from Batteries *) let range startv endv = let s,e = (min startv endv),(max startv endv) in let rec aux acc = function n -> if n=s then n::acc else aux (n::acc) (n-1) in aux [] e (* create a shadow file descriptor *) let tempfd () = let name = Filename.temp_file "mmap" "TMP" in try let fd = Unix.openfile name [Unix.O_RDWR; Unix.O_CREAT] 0o600 in Unix.unlink name; fd with e -> Unix.unlink name; raise e parmap-1.1.1/src/parmap_utils.mli000066400000000000000000000004161361257663500170030ustar00rootroot00000000000000val log_error : ('a, unit, string, unit) format4 -> 'a val append_tr : 'a list -> 'a list -> 'a list val concat_tr : 'a list list -> 'a list val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b val range : int -> int -> int list val tempfd : unit -> Unix.file_descr parmap-1.1.1/src/setcore.ml000066400000000000000000000003161361257663500155750ustar00rootroot00000000000000(* uses the native affinity interface to declare that the current process should be attached to core number n *) external numcores: unit -> int = "numcores" external setcore: int -> unit = "setcore" parmap-1.1.1/src/setcore_stubs.c000066400000000000000000000032251361257663500166310ustar00rootroot00000000000000#include "setcore_stubs.h" #if HAVE_MACH_THREAD_POLICY_H #include #include // #include #endif #if HAVE_DECL_SCHED_SETAFFINITY #define _GNU_SOURCE #include #endif #include #include #include #include CAMLprim value numcores(value unit) { int numcores = sysconf( _SC_NPROCESSORS_ONLN ); return Val_int(numcores); } CAMLprim value setcore(value which) { int numcores = sysconf( _SC_NPROCESSORS_ONLN ); int w = Int_val(which) % numcores; // stay in the space of existing cores #if HAVE_DECL_SCHED_SETAFFINITY cpu_set_t cpus; #endif #if HAVE_MACH_THREAD_POLICY_H thread_affinity_policy_data_t affinityData; #endif int retcode; int finished=0; while (finished==0) { #if HAVE_DECL_SCHED_SETAFFINITY CPU_ZERO(&cpus); CPU_SET (w,&cpus); //fprintf(stderr,"Trying to pin to cpu %d out of %d reported by the system\n",w,numcores); retcode = sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpus); if(retcode != 0) { fprintf(stderr,"Failed pinning to cpu %d, trying %d/2\n",w, w); w=w/2; } else #endif #if HAVE_MACH_THREAD_POLICY_H affinityData.affinity_tag = w; retcode = thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY, &affinityData, THREAD_AFFINITY_POLICY_COUNT); if(retcode) { fprintf(stderr,"MAC OS X: Failed pinning to cpu %d, trying %d/2\n",w, w); w=w/2; } else #endif { //fprintf(stderr,"Succeeded pinning to cpu %d\n",w); finished=1; } } return Val_unit; } parmap-1.1.1/tests/000077500000000000000000000000001361257663500141525ustar00rootroot00000000000000parmap-1.1.1/tests/LICENCE000066400000000000000000000432541361257663500151470ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. parmap-1.1.1/tests/dune000066400000000000000000000005241361257663500150310ustar00rootroot00000000000000(library (name utils) (modules utils) (flags (:standard -w -35-27)) (libraries parmap)) (tests (names floatscale simplescale simplescale_array simplescalefold simplescalemapfold) (modules floatscale simplescale simplescale_array simplescalefold simplescalemapfold) (flags (:standard -w -35-27)) (libraries utils parmap)) parmap-1.1.1/tests/floatscale.ml000066400000000000000000000042131361257663500166210ustar00rootroot00000000000000(**************************************************************************) (* Sample use of Parmap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap open Utils (* from Paul Vernaza's code *) let env_param of_string name default = try of_string (Unix.getenv name) with Not_found -> default let env_num = env_param float_of_string let env_float = env_num let env_int = env_param int_of_string let env_bool = env_param bool_of_string let env_string = env_param (fun x -> x) let nIters = env_int "nIters" 1 let nData = env_int "nData" 10000000 let nProcs = env_int "nProcs" 8 let inOrder = env_bool "inOrder" false let chunksize = env_int "chunksize" (nData/nProcs) let xs, func = let xs = Array.make nData 0. in let pi = 4. *. atan 1. in for i = 0 to nData - 1 do xs.(i) <- pi *. (float_of_int i /. (float_of_int nData)) done; xs, (fun x -> cos (sqrt x)) let checksum_array arr () = Array.fold_left (fun acc el -> acc +. el) 0. arr;; let checksum_list list () = List.fold_left (fun acc el -> acc +. el) 0. list;; Printf.printf "Test: normal parmap\n%!";; scale_test ~chunksize:chunksize ~inorder:inOrder func (A xs) nIters nProcs nProcs;; Printf.printf "Test: specialised array parmap\n%!";; array_scale_test ~chunksize:chunksize ~inorder:inOrder func xs nIters nProcs nProcs;; Printf.printf "Test: specialised float array parmap\n%!";; array_float_scale_test ~chunksize:chunksize ~inorder:inOrder func xs nIters nProcs nProcs;; parmap-1.1.1/tests/simplescale.ml000066400000000000000000000071751361257663500170170ustar00rootroot00000000000000(**************************************************************************) (* Sample use of Parmap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap open Utils let initsegm n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n ;; let compute p = let r=ref 1 in for i = 1 to 80000 do r:= !r+(p*p)-(p*(p-1)) done; !r ;; let fcompute p = let r=ref 1. in for i = 1 to 80000 do r:= !r+.(p*.p)-.(p*.(p-.1.)) done; !r ;; Printf.printf "*** Checking corner cases: call on empty lists and arrays must not raise an exception\n%!"; Printf.printf "* parmap []\n%!"; parmap (fun x -> x) (L []);; Printf.printf "* parmap [| |]\n%!"; parmap (fun x -> x) (A [| |]);; Printf.printf "* pariter []\n%!"; pariter (fun x -> ()) (L []);; Printf.printf "* pariter [| |]\n%!"; pariter (fun x -> ()) (A [| |]);; Printf.printf "*** Checking the code for non tail recursive calls: an exception here indicates there are some left\n%!"; scale_test (fun x -> x) (L (initsegm 10000000)) 1 2 2;; Printf.printf "*** Checking that we properly parallelise execution if we have less tasks than cores: if you do not see 5 processes, there is a problem\n%!"; debugging true;; (* scale_test (fun x -> x) (L (initsegm 5)) 1 8 8;; *) Printf.printf "* Simplemapper 8 cores, 5 elements\n%!"; ignore(parmap ~ncores:8 (fun x -> x) (L (initsegm 5)));; Printf.printf "* Simpleiter 8 cores, 5 elements\n%!"; ignore(pariter ~ncores:8 (fun x -> ()) (L (initsegm 5)));; Printf.printf "*** Checking that we properly handle bogus core numbers\n%!"; Printf.printf "* Simplemapper 0 cores\n%!"; ignore(parmap ~ncores:0 (fun x -> x) (L (initsegm 5)));; Printf.printf "* Simpleiter 0 cores\n%!"; ignore(pariter ~ncores:0 (fun x -> ()) (L (initsegm 5)));; debugging false;; Printf.printf "*** Computations on integer lists\n%!"; scale_test compute (L (initsegm 20000)) 2 1 10;; Printf.printf "*** Computations on integer lists (chunksize=100)\n%!"; scale_test ~chunksize:100 ~inorder:false compute (L (initsegm 20000)) 2 1 10;; Printf.printf "*** Computations on integer arrays\n%!"; scale_test compute (A (Array.init 20000 (fun n -> n+1))) 2 1 10;; Printf.printf "*** Computations on integer arrays (chunksize-100)\n%!"; scale_test ~chunksize:100 ~inorder:false compute (A (Array.init 20000 (fun n -> n+1))) 2 1 10;; Printf.printf "*** Computations on lists of floats\n%!"; scale_test fcompute (L (List.map float_of_int (initsegm 20000))) 2 1 10;; Printf.printf "*** Computations on lists of floats (chunksize=100)\n%!"; scale_test ~chunksize:100 ~inorder:false fcompute (L (List.map float_of_int (initsegm 20000))) 2 1 10;; Printf.printf "*** Computations on arrays of floats\n%!"; scale_test fcompute (A (Array.init 20000 (fun n -> float_of_int (n+1)))) 2 1 10;; Printf.printf "*** Computations on arrays of floats (chunksize=100)\n%!"; scale_test ~chunksize:100 ~inorder:false fcompute (A (Array.init 20000 (fun n -> float_of_int (n+1)))) 2 1 10;; parmap-1.1.1/tests/simplescale_array.ml000066400000000000000000000026101361257663500202020ustar00rootroot00000000000000(**************************************************************************) (* Sample use of Parmap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap open Utils let compute p = let r=ref 1 in for i = 1 to 80000 do r:= !r+(p*p)-(p*(p-1)) done; !r ;; let fcompute p = let r=ref 1. in for i = 1 to 80000 do r:= !r+.(p*.p)-.(p*.(p-.1.)) done; !r ;; array_scale_test fcompute (Array.init 20000 (fun i -> float_of_int i)) 2 1 10;; array_float_scale_test fcompute (Array.init 20000 (fun i -> float_of_int i)) 2 1 10;; scale_test ~chunksize:100 ~inorder:false compute (A (Array.init 20000 (fun i -> i))) 2 1 10;; scale_test compute (A (Array.init 20000 (fun i -> i))) 2 1 10;; parmap-1.1.1/tests/simplescalefold.ml000066400000000000000000000036521361257663500176600ustar00rootroot00000000000000(**************************************************************************) (* Sample use of Parmap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap let initsegm n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n ;; let scale_test iter nprocmin nprocmax = Printf.eprintf "Testing scalability with %d iterations on %d*2 to %d*2 cores\n" iter nprocmin nprocmax; Printf.eprintf "The fold operation in this example is too simple to scale: this is just a test for the code.\n"; let l = initsegm 20000 in let cl,tseq = let d=Unix.gettimeofday() in let l' = List.fold_right (+) l 0 in l',(Unix.gettimeofday() -. d) in Printf.eprintf "Sequential execution takes %f seconds\n" tseq; for i = nprocmin to nprocmax do let tot=ref 0.0 in for j=1 to iter do let d=Unix.gettimeofday() in let cl'=parfold ~ncores:(i*2) (+) (L l) 0 (+) in tot:=!tot+.(Unix.gettimeofday()-.d); if cl<>cl' then Printf.eprintf "Parfold failure: result mismatch\n" done; let speedup=tseq /. (!tot /. (float iter)) in Printf.eprintf "Speedup with %d cores (average on %d iterations): %f (tseq=%f, tpar=%f)\n" (i*2) iter speedup tseq (!tot /. (float iter)) done ;; scale_test 2 1 10;; parmap-1.1.1/tests/simplescalemapfold.ml000066400000000000000000000037131361257663500203540ustar00rootroot00000000000000(**************************************************************************) (* Sample use of Parmap, a simple library to perform Map computations on *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap let initsegm n = let rec aux acc = function 0 -> acc | n -> aux (n::acc) (n-1) in aux [] n ;; let compute p = let r=ref 1 in for i = 1 to 80000 do r:= !r+(p*p)-(p*(p-1)) done; !r ;; let scale_test iter nprocmin nprocmax = Printf.eprintf "Testing scalability with %d iterations on %d*2 to %d*2 cores\n" iter nprocmin nprocmax; let l = initsegm 20000 in let cl,tseq = let d=Unix.gettimeofday() in let l' = List.fold_right (+) (List.map compute l) 0 in l',(Unix.gettimeofday() -. d) in Printf.eprintf "Sequential execution takes %f seconds\n" tseq; for i = nprocmin to nprocmax do let tot=ref 0.0 in for j=1 to iter do let d=Unix.gettimeofday() in let cl'=parmapfold ~ncores:(i*2) ~chunksize:100 compute (L l) (+) 0 (+) in tot:=!tot+.(Unix.gettimeofday()-.d); if cl<>cl' then Printf.eprintf "Parmap failure: result mismatch\n" done; let speedup=tseq /. (!tot /. (float iter)) in Printf.eprintf "Speedup with %d cores (average on %d iterations): %f (tseq=%f, tpar=%f)\n" (i*2) iter speedup tseq (!tot /. (float iter)) done ;; scale_test 2 1 10;; parmap-1.1.1/tests/utils.ml000066400000000000000000000114211361257663500156430ustar00rootroot00000000000000(**************************************************************************) (* Generic testing framework for evaluating speedup on Parmap *) (* a multi-core *) (* *) (* Author(s): Roberto Di Cosmo *) (* *) (* This program is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, either version 2 of the *) (* License, or (at your option) any later version. *) (**************************************************************************) open Parmap let scale_test ?(init=(fun _ -> ())) ?(inorder=true) ?(step=1) ?chunksize compute sequence iter nprocmin nprocmax = Printf.eprintf "Testing scalability with %d iterations on %d to %d cores, step %d\n%!" iter nprocmin nprocmax step; let rseq,tseq = let d=Unix.gettimeofday() in match sequence with L l -> let l'=List.rev_map compute l in List.rev l',(Unix.gettimeofday() -. d) | A a -> let l'=Array.to_list(Array.map compute a) in l',(Unix.gettimeofday() -. d) in Printf.eprintf "Sequential execution takes %f seconds\n%!" tseq; for incr = 0 to (nprocmax-nprocmin)/step do let i = nprocmin + incr in let tot=ref 0.0 in for j=1 to iter do let d=Unix.gettimeofday() in let rpar=parmap ~init ~ncores:i ?chunksize compute sequence in tot:=!tot+.(Unix.gettimeofday()-.d); if rseq<>rpar then begin if (List.sort compare rseq) <> (List.sort compare rpar) then Printf.eprintf "Parmap failure: result mismatch!\n%!" else if inorder then Printf.eprintf "Parmap failure: result order was expected to be preserved, and is not.\n%!" else Printf.eprintf "Parmap warning: result order is not preserved (it was not expected to be).\n%!" end done; let speedup=tseq /. (!tot /. (float iter)) in Printf.eprintf "Speedup with %d cores (average on %d iterations): %f (tseq=%f, tpar=%f)\n%!" i iter speedup tseq (!tot /. (float iter)) done; rseq ;; let array_scale_test ?(init= (fun _ -> ())) ?(inorder=true) ?(step=1) ?chunksize compute a iter nprocmin nprocmax = Printf.eprintf "Testing scalability with %d iterations on %d to %d cores, step %d\n" iter nprocmin nprocmax step; let rseq,tseq = let d=Unix.gettimeofday() in let a'= Array.map compute a in a',(Unix.gettimeofday() -. d) in Printf.eprintf "Sequential execution takes %f seconds\n" tseq; for incr = 0 to (nprocmax-nprocmin)/step do let i = nprocmin + incr in let tot=ref 0.0 in for j=1 to iter do let d=Unix.gettimeofday() in let rpar=array_parmap ~init ~ncores:i compute a in tot:=!tot+.(Unix.gettimeofday()-.d); if rseq<>rpar then begin if (Array.sort compare rseq) <> (Array.sort compare rpar) then Printf.eprintf "Parmap failure: result mismatch!\n" else if inorder then Printf.eprintf "Parmap failure: result order was expected to be preserved, and is not.\n" else Printf.eprintf "Parmap warning: result order is not preserved (it was not expected to be).\n" end done; let speedup=tseq /. (!tot /. (float iter)) in Printf.eprintf "Speedup with %d cores (average on %d iterations): %f (tseq=%f, tpar=%f)\n%!" i iter speedup tseq (!tot /. (float iter)) done; rseq ;; let array_float_scale_test ?(init= (fun _ -> ())) ?(inorder=true) ?(step=1) ?chunksize compute a iter nprocmin nprocmax = Printf.eprintf "Testing scalability with %d iterations on %d to %d cores, step %d\n" iter nprocmin nprocmax step; let rseq,tseq = let d=Unix.gettimeofday() in let a'= Array.map compute a in a',(Unix.gettimeofday() -. d) in Printf.eprintf "Sequential execution takes %f seconds\n" tseq; for incr = 0 to (nprocmax-nprocmin)/step do let i = nprocmin + incr in let tot=ref 0.0 in for j=1 to iter do let d=Unix.gettimeofday() in let rpar=array_float_parmap ~init ~ncores:i compute a in tot:=!tot+.(Unix.gettimeofday()-.d); if rseq<>rpar then begin if (Array.sort compare rseq) <> (Array.sort compare rpar) then Printf.eprintf "Parmap failure: result mismatch!\n" else if inorder then Printf.eprintf "Parmap failure: result order was expected to be preserved, and is not.\n" else Printf.eprintf "Parmap warning: result order is not preserved (it was not expected to be).\n" end done; let speedup=tseq /. (!tot /. (float iter)) in Printf.eprintf "Speedup with %d cores (average on %d iterations): %f (tseq=%f, tpar=%f)\n%!" i iter speedup tseq (!tot /. (float iter)) done; rseq ;;