1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35
C Program - test.c:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
long sum = 0;
int V = atoi(argv[1]);
for (int C=1; C<=V; ++C) {
for (int c=1; c<C+1; ++c) {
sum = sum + c;
}
}
printf("sum = %li\n",sum);
return 0;
}
Swift Program - test.swift:
var sum = 0;
var V = Int(Process.arguments[1])
for var C = 1; C <= V; ++C {
for var c = 1; c < C+1; ++c {
sum = sum + c;
}
}
print("sum = \(sum)");
Go Program - test.go:
package main
import "os"
import "fmt"
import "strconv"
func main() {
sum := 0
V,err := strconv.Atoi(os.Args[1])
for I:=1; I<=V; I++ {
for i:=1; i<I+1; i++ {
sum = sum + i
}
}
if err == nil {
fmt.Println("sum =",sum)}
}
Python C extension: Say we want to create a module named "pal" with a function called "f1" to just do the same as test.c
Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args)
{
int x;
PyArg_ParseTuple(args, "i", &x);
long sum = 0;
for (int C=1; C<=x; ++C)
{
for (int c=1; c<C+1; ++c)
{
sum = sum + c;
}
}
return Py_BuildValue("l", sum);
}
static PyMethodDef PalMethods[] = {
{"f1", pal_f1, METH_VARARGS},
{NULL, NULL}
};
static struct PyModuleDef palmodule = {
PyModuleDef_HEAD_INIT,
"pal", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
PalMethods
};
PyMODINIT_FUNC PyInit_pal(void)
{
return PyModule_Create(&palmodule);
}
from distutils.core import setup, Extension
setup(name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])
Step 3. Install the extension using the following command:
sudo python3 setup.py install
Step 4. Now write a python program "testc.py" using the pal module:
#!/usr/bin/python3
from sys import argv
from pal import f1
print("sum = %s" %f1(int(argv[1])))
Runtime Performance Comparison
Run the above four different programs one by one and find the time taken as shown below. The number used is 100,000 :
1. C program
$ time ./test.o 100000
sum = 166671666700000
real 0m10.999s
user 0m10.992s
sys 0m0.000s
2. Swift program
$ time ./test.sw 100000sum = 166671666700000
real 0m19.318s
user 0m19.304s
sys 0m0.000s
3. Go program
$ time ./test.g 100000
sum = 166671666700000
real 0m2.155s
user 0m2.152s
sys 0m0.004s
$ time ./testc.py 100000
sum = 166671666700000
real 0m1.618s
user 0m1.616s
sys 0m0.000s
This shows that Python with C extension is the best that takes the least time. The second best is "Go", then "C". Swift is the worst among them.
No comments:
Post a Comment